简体   繁体   English

如何通过在 JavaScript 中使用 POST 方法获取 API 的访问令牌?

[英]How to get access token for an API by using POST method in JavaScript?

The API I want to get credentials for uses OAuth2.我想获取使用 OAuth2 凭据的 API。 The documentation for the API has this listed: API 的文档列出了以下内容:

Request access token:

POST: auth/access_token

Url Parms:
grant_type    : "client_credentials"
client_id     :  Client id
client_secret :  Client secret

What I figured from this is that I need to send a JSON object as a string so I tried this in JavaScript.我从中想到的是,我需要将 JSON 对象作为字符串发送,所以我在 JavaScript 中尝试了这个。

var xhr = new XMLHttpRequest();
    xhr.open("POST","url for the api",false);
    
    var obj = {
       
       "POST": "auth/access_token",
       "Url Parms": [   
          {
             "grant_type":'\"client_credentials\"',
             "client_id": "My Client id",
             "client_secret": "My Client secret"
          }
       ]
    };
    
    var clientcred = JSON.stringify(obj);
    xhr.send(obj);

All this gave me was a JSON which said I made an error.所有这些给了我一个 JSON,它说我犯了一个错误。

{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant_type\" parameter."}

The code actually doesn't even work because of 'same-origin policy'.由于“同源策略”,该代码实际上甚至不起作用。 I used an extension to get around that.我使用了一个扩展来解决这个问题。 But I am so done.但我已经完成了。 I can't figure it out.我想不通。 Do I need to learn something like php?我需要学习像php这样的东西吗? How do I get my access token.我如何获得我的访问令牌。

Edit:编辑:

It might need the parameters in the URL, so POST auth/access_token?grant_type=client_credentials&client_id=id‌​&client_secret=clien‌​t_secret or possibly POST auth/access_token/client_credentials/id/client_secret – Sara Tibbetts 8 hours ago它可能需要 URL 中的参数,因此 POST auth/access_token?grant_type=client_credentials&client_id=id‌ &client_secret=clien‌ t_secret 或 POST auth/access_token/client_credentials/id/client_secret – Sara Tibbetts 8 小时前

This did it.这做到了。 I woke up and the first thing I tried and it worked.我醒来,第一件事就是尝试,它奏效了。 Thank you so much @Sara Tibbetts and everyone else who tried to help me.非常感谢@Sara Tibbetts 和所有试图帮助我的人。

Edit 2:编辑2:

The extension was a poor workaround, since then I have learned about Cross Origin Resource Sharing.扩展是一个糟糕的解决方法,从那时起我了解了跨源资源共享。 I should've made my API call from the server rather than doing it client side, which is actually secure as well.我应该从服务器调用 API 而不是在客户端调用,这实际上也是安全的。

This is how I'm doing it in a working Prod program (It is using an auth code that I get earlier - but it doesn't matter, it's just different parameters - replace my stuff that has auth code with client secret requirements and give it a try..I think you're just trying too hard.这就是我在一个工作 Prod 程序中的做法(它使用的是我之前得到的授权码——但没关系,只是不同的参数——用客户端秘密要求替换我的具有授权码的东西,并给出这是一个尝试..我认为你只是太努力了。

var xhr = new XMLHttpRequest();

I use a string for my parameters:我使用一个字符串作为我的参数:

var data =
'resource=[my resource]' +
'&client_id=' + clientId +
'&code=' + authCode +
'&grant_type=authorization_code' +
'&response_type=token';
var dataFinal = encodeURI(data);

Then I POST it as:然后我将其发布为:

xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', '[something]');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        //do something
    }
}
xhr.send(dataFinal);

You can try something like the below.您可以尝试以下操作。 Actually the json needs to be set to the data property.实际上需要将 json 设置为 data 属性。

$.ajax({
type: 'POST',
url: 'https://url.com',
crossDomain: true,
data: JSON.stringify({grant_type    : "client_credentials",
    client_id     :  "My Client id",
    client_secret :  "My Client secret"}),
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData);
},
error: function (responseData, textStatus, errorThrown) {
    alert('POST failed.');
}});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM