Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending post request from axios with "Content-Type" : "application/x-www-form-urlencoded" gives an 401 Unauthorized response

Tags:

node.js

axios

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.

like image 918
lasith eshan Avatar asked Mar 19 '19 13:03

lasith eshan


1 Answers

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.)

like image 120
binary lobster Avatar answered Sep 21 '22 04:09

binary lobster