Ryan Skene
Ryan Skene

Reputation: 924

post works with request module but not axios

Burned two hours of my life on this and wondering if fresh eyes can help.

I am attempting to contact auth0 to get access token for the management API.

The provide sample code, using request module, which works perfectly (I have replaced the key/secret values):

var request = require("request");

var options = { method: 'POST',
  url: 'https://dev-wedegpdh.auth0.com/oauth/token',
  headers: { 'content-type': 'application/json' },
  body: '{"client_id":"myID","client_secret":"mySecret","audience":"https://dev-wedegpdh.auth0.com/api/v2/","grant_type":"client_credentials"}' };

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  res.json(JSON.parse(response.body).access_token)
});

I have my ID and Secret stored in .env file, so was able to adjust to this, which also works fine:

var options = { method: 'POST',
    url: 'https://dev-wedegpdh.auth0.com/oauth/token',
    headers: { 'content-type': 'application/json' },
    body: 
      JSON.stringify({
        grant_type: 'client_credentials',
        client_id: process.env.auth0AppKey,
        client_secret: process.env.auth0AppSecret,
        audience: 'https://dev-wedegpdh.auth0.com/api/v2/'})
  }

  request(options, function (error, response, body) {
    if (error) throw new Error(error)
    res.json(JSON.parse(response.body).access_token)
  })

I try to make the exact same request using axios and I receive 404 error:

let response = await axios.post(
  'https://dev-wedegpdh.auth0.com/api/v2/oauth/token', 
  JSON.stringify({
    grant_type: 'client_credentials',
    client_id: process.env.auth0AppKey,
    client_secret: process.env.auth0AppSecret,
    audience: 'https://dev-wedegpdh.auth0.com/api/v2/'
  }),
  { 
    headers: {'content-type': 'application/json'},
  }
)

I have tried several different formats or configurations for the post function including those found here and here etc.

Anyone see what I am doing wrong???

Upvotes: 0

Views: 79

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

In axios post body, you need to send data as JSON, no need to use JSON.stringify.

let response = await axios.post(
  "https://dev-wedegpdh.auth0.com/api/v2/oauth/token",
  {
    grant_type: "client_credentials",
    client_id: process.env.auth0AppKey,
    client_secret: process.env.auth0AppSecret,
    audience: "https://dev-wedegpdh.auth0.com/api/v2/"
  },
  {
    headers: { "content-type": "application/json" }
  }
);

Upvotes: 2

Related Questions