6
votes

I am sending a POST request to a server to fetch a token through axios with a Content-Type header of x-www-form-urlencoded. I tried the same with postman and it works fine. I'm sending a key value pair of grant_type and client_credentials in the request body.

This is my axios request:

axios.post(`${baseURI}/protocol/openid-connect/token`, data, {
  headers : {
    "Authorization" : "Basic " + token,
    "Content-Type" : "application/x-www-form-urlencoded"
  },
  withCredentials: true
}).then(response => {
  AUTH_TOKEN = response.data.access_token;
  console.log(response.data);
}).catch(error => {
  console.log(error.response);
})

The data object consists of the client_credentials.The same credentials gives a successful response in postman.

1

1 Answers

12
votes

I had this exact same problem until I finally figured out that Axios needed the data object to be reformatted as a query string.

So make yourself a function like this:

function getQueryString(data = {}) {
  return Object.entries(data)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
}

Pretty simple, just URI encoding all the parts of your object and joining them with &.

Then modify your code like this:

axios.post(`${baseURI}/protocol/openid-connect/token`,data, {
  headers : {
    "Authorization" : "Basic " + token,
    "Content-Type" : "application/x-www-form-urlencoded"
  },
  withCredentials: true,
  transformRequest: getQueryString
})
.then(/*...*/);

You can read about the different options, including transformRequest, for the request config here: https://github.com/axios/axios#request-config

(I'm still annoyed that this was necessary and not just handled by Axios but oh well.)