使用 Axios Node.js 请求 oAuth2 令牌 - 使用“请求”有效,但不适用于 Axios

Tim*_*ore 2 client credentials node.js oauth-2.0 axios

以下代码工作正常:

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);
});
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用 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);
  });
Run Code Online (Sandbox Code Playgroud)

ie catch 获取错误响应 401

关于如何将成功的“请求”编码到 axios 中的任何想法?

Tim*_*ore 5

上面建议的解决方案解决了问题。解决方案如下所示:

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);
    }); 
Run Code Online (Sandbox Code Playgroud)