以下代码工作正常:
request({
url: 'https://xxxxxxx/oauth/token',
method: 'POST',
auth: {
user: 'clientId',
pass: 'clientSecret'
},
form: {
'grant_type': 'client_credentials'
}
}, function(err, res) {
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
但是,当我尝试使用 Axios 复制它时(因为请求现在已弃用),我不断收到 401
axios.request({
url: 'https://xxxxxxx/oauth/token',
method: 'POST',
auth: {
username: 'clientId',
password: 'clientSecret',
},
headers: {
Accept: 'application/json','Content-Type':'application/x-www-form-urlencoded',
},
data: {
grant_type: 'client_credentials',
},
}).then(function(res) {
console.log(res);
}).catch(function(err) {
console.log("error = " + err);
});
即catch 拾取错误响应 401
关于如何将成功的“请求”编码到 axios 中的任何想法??
最佳答案
上面建议的解决方案解决了问题。解决方案如下所示:
const qs = require('querystring');
const data = { 'grant_type': 'client_credentials'};
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth:{
username: 'clientId',
password: 'clientSecret',
},
data: qs.stringify(data),
url: 'https://xxxxxxxxx/oauth/token',
}
axios.request(options).then(function(res) {
console.log(res);
}).catch(function(err) {
console.log("error = " + err);
});
关于node.js - 使用 Axios Node.js 请求 oAuth2 token - 使用 'request' 但不适用于 Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65278914/