我用下面的JS脚本总是得到 "grant_type is required error invalid_request",我不知道为什么。
let tokenUrl = 'myTokenURL';
let clientId = 'myClientID';
let clientSecret = 'myClientSecret';
let scope = 'myScope';
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
auth: {
type: "basic",
basic: [
{ key: "username", value: clientId },
{ key: "password", value: clientSecret }
]
},
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'formdata',
formdata: [
{ key: "grant_type", value: "authorization_code" },
{ key: 'scope', value: scope },
{ key: 'redirect_uri', value: 'MyRedirectURI' },
{ key: 'client_id', value: clientId},
{ key: 'clientSecret', value: clientSecret},
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = jsonResponse = response.json();;
let newAccessToken = jsonResponse.access_token;
console.log({ err, jsonResponse, newAccessToken })
});
这个脚本使用的是Postman的sendRequest函数
对于那些对这个问题有兴趣的人,请看下面的代码,它实际上就是上面评论中Danny Daiton的答案。
let tokenUrl = 'myTokenURL';
let clientId = 'myClientID';
let clientSecret = 'myClientSecret';
let scope = 'myScope';
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
auth: {
type: "basic",
basic: [
{ key: "username", value: clientId },
{ key: "password", value: clientSecret }
]
},
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "authorization_code" },
{ key: 'scope', value: scope },
{ key: 'redirect_uri', value: 'MyRedirectURI' },
{ key: 'client_id', value: clientId},
{ key: 'clientSecret', value: clientSecret},
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = jsonResponse = response.json();;
let newAccessToken = jsonResponse.access_token;
console.log({ err, jsonResponse, newAccessToken })
});