ORCID / simple-orcid-auth-node

MIT License
2 stars 0 forks source link

"request" library is deprecated, Axios POST request returns code 401 #4

Open martijnende opened 2 years ago

martijnende commented 2 years ago

Since request is deprecated (see this issue), I am looking for an alternative to make POST requests in client-app.js. One good alternative is axios, but when trying to replicate the original code, I keep getting 401 status codes.

The original code using request is:

// function to render page after making request
var exchangingCallback = function(error, response, body) {
if (error == null) // No errors! we have a token :-)
  res.render('pages/token', { 'body': JSON.parse(body) });
else // handle error
  res.render('pages/error', { 'error': error });
};

// config for exchanging code for token 
var exchangingReq = {
  url: config.TOKEN_EXCHANGE_URI,
  method: 'post',
  body: querystring.stringify({
    'code': req.query.code,
    'client_id': config.CLIENT_ID,
    'client_secret': config.CLIENT_SECRET,
    'grant_type': 'authorization_code',
  }),
  headers: {
    'content-type': 'application/x-www-form-urlencoded; charset=utf-8'
  }
}

//making request exchanging code for token
request(exchangingReq, exchangingCallback);

My attempt at replicating the results with axios is:

const data = {
  "client_id": config.CLIENT_ID,
  "client_secret": config.CLIENT_SECRET,
  "grant_type": "authorization_code",
  "code": req.query.code,
}

const headers = {
  "accept": "application/json",
  "content-type": "application/x-www-form-urlencoded; charset=utf-8",
};

axios.post(
  config.TOKEN_EXCHANGE_URI, data, headers
).then(body => {
  res.render('pages/token', { 'body': JSON.parse(body) });
}).catch(error => {
  res.render('pages/error', { 'error': error });
});

Based on these instructions for the public API, I don't quite understand why the axios POST request is not accepted. The credentials are identical as for the request approach, which works.

tnhung2011 commented 2 years ago

I'm not a Node.js developer (because I'm using a potato laptop which is bad for programming purposes) but you can consider to try using HTTPie instead.

martijnende commented 2 years ago

Thanks for the suggestion. I tried HTTPie, which gives me the same result as Axios