node.js - 使用 Axios Node.js 请求 oAuth2 token - 使用 'request' 但不适用于 Axios

标签 node.js oauth-2.0 axios client credentials

以下代码工作正常:

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/

相关文章:

node.js - AWS 弹性 beanstalk 上的 spawn casperjs ENOENT 错误

javascript - 没有命名空间污染的模块化客户端 Javascript 的方法

javascript - request post 与 axios post 解析不同的结果

javascript - 在 Nestjs 中使用 https 和 Axios 请求

vue.js - Vue Axios 动态 URL

node.js - 使用 casperjs/phantomjs 登录 Amazon Developer 网页

node.js - 通过 Node.JS 连接 RedisToGo

oauth-2.0 - 如果有人丢失了装有 Google Authenticator 或 Authy 的手机,会发生什么情况?

azure - 如何验证 Azure Active Directory 中刷新的 id_token 的签名

oauth-2.0 - Google 访问 token 过期时间