axios.post results in Bad request - grant_type:'client_credentials'
Asked Answered
P

1

6

My axios POST method is not working fine. While the call syntax appears to be correct, I guess there is somewhat deep-rooted issue in my specific case. I am trying to get access token using grant_type=client_credentials, using a POST request to fiware IDM server. The call results in 400: bad request.

curl command works just great. It seems there is a CORS violation when I use simple http request, hence I switched to using node. I tried axios by sending data in separate body, it didn't work either, then someone suggested to send the data in the call using axios.post, it also ended in same problem. Note: I have tried grant_type=password, however, that also met same fate.

axios.post('https://account.lab.fiware.org/oauth2/token',{ 
'grant_type':'client_credentials'},{
headers: 
{
'Content-Type':'application/x-www-form-urlencoded',     
'Authorization': 'Basic xxxx'   
}

}).then((response) => {
    console.log(response);
    }).catch((error) =>{
    console.log(error.response.data.error);
    })

I expect to get the access token, however, I am getting error 400 as below:

{ message: 'grant_type missing in request body: {}',
code: 400,
title: 'Bad Request' }
Plasmo answered 7/4, 2019 at 9:39 Comment(3)
could you also post the working curl?Publisher
Sure.. here it..Plasmo
curl -v --insecure -X POST account.lab.fiware.org/oauth2/token -H "Content-Type:application/x-www-form-urlencoded" -H "Authorization:Basic xxxx" -d "grant_type=client_credentials"Plasmo
P
12

The issue is because the host at https://account.lab.fiware.org/oauth2/token expects body data to be x-www-form-urlencoded but axios is converting the body to json for you. That is the default behaviour with axios.

Change your axios code to send x-www-form-urlencoded body data like:

// use querystring node module
var querystring = require('querystring');

axios.post('https://account.lab.fiware.org/oauth2/token',{
  // note the use of querystring
  querystring.stringify({'grant_type':'client_credentials'}),{
  headers: {
    'Content-Type':'application/x-www-form-urlencoded',     
    'Authorization': 'Basic xxxx'   
  }
}).then(...
Publisher answered 7/4, 2019 at 9:50 Comment(2)
Problem is with raw query string. So after using querystring.stringify({'grant_type':'client_credentials'}) It worked perfectly.Astrodome
thanks! tried to edit now, too many edits pending... please can someone remove the curly at the end of the 2nd line of code. Shouldn't be thereBlasting

© 2022 - 2024 — McMap. All rights reserved.