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

Using Axios Node.js to request an oAuth2 token

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

Following code works fine:

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);
});

However, when I try and replicate this using Axios (as request is now deprecated) i keep getting a 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);
  });

i.e. catch picks up the error response 401

Any ideas on how to code the successful 'request' into axios ??

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

By default axios sends data in JSON format. To send form data you need to use URLSearchParams or qs.stringify.

See Using application/x-www-form-urlencoded format