我正在尝试使用AJAX来请求令牌。这只会在localhost上用于发出请求。我有代码:
$.ajax({
url: "TOKEN URL HERE",
beforeSend: function(xhr) {
xhr.setRequestHeader("grant_type", "client_credentials");
xhr.setRequestHeader("client_id", "ENTER CLIENT ID");
xhr.setRequestHeader("client_secret", "ENTER CLIENT SECRET");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
},
dataType: "json",
//content-Type: "application/json",
type: "POST",
success: function(response) {
token = response.access_token;
expiresIn = response.expires_in;
},
error: function(errorThrown) {
alert(errorThrown.error);
}
});
但是,它不起作用。这是正确的方法还是我的参数不正确? (或者是使用AJAX / JQuery / JS无法实现的OAuth2令牌请求)
确定,grant_type,client_id,client_secret应该通过标头而不是有效负载传递?
尝试从标题中删除它们(左接受,仅限内容类型),然后使用其余参数添加“data”属性。
像这样的东西:
$.ajax({
url: "TOKEN URL HERE",
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
},
dataType: "json",
data: {
client_id: "ENTER CLIENT ID",
client_secret: "ENTER CLIENT SECRET",
grant_type: "client_credentials"
},
type: "POST",
success: function(response) {
token = response.access_token;
expiresIn = response.expires_in;
},
error: function(errorThrown) {
alert(errorThrown.error);
}
});