Axios Post Method to implement customized headers and with token value

200 Views Asked by At

I'm trying to write a Post method with Axios in NodeJS.

I have following things to pass as param in post method

url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'

As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.

var config = {
 headers: {'Authorization': "bearer " + token}
};

var bodyParameters = {
  data 'grant_type=password&username=user123&password=password123'   
}

Axios.post( 
 'http:/xyz/oauthToken',
 bodyParameters,
 config
).then((response) => {
   console.log(response)
}).catch((error) => {
  console.log(error)
});     

Any help/suggestion would be appreciated :-)

1

There are 1 best solutions below

2
On

Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.

const querystring = require('querystring');

const body = querystring.stringify({ 
  grant_type: 'password',
  username: 'user123',
  password: 'password123'
});

axios.post('http:/xyz/oauthToken', body, { 
  headers: {
    authorization: `bearer ${token}`,
    'content-type': 'application/x-www-form-urlencoded'
  }
});