Warm tip: This article is reproduced from serverfault.com, please click

oauth 2.0-使用Axios Node.js请求oAuth2令牌

(oauth 2.0 - Using Axios Node.js to request an oAuth2 token)

发布于 2020-12-13 18:02:22

以下代码可以正常工作:

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的任何想法?

Questioner
Tim Cashmore
Viewed
11
Anatoly 2020-12-14 02:09:48

默认情况下,axios以JSON格式发送数据。要发送表格数据,你需要使用URLSearchParamsqs.stringify

请参阅使用application / x-www-form-urlencoded格式