Axios Http client - How to construct Http Post url with form params

Javascriptnode.jsAxios

Javascript Problem Overview


I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below:

JAVA CODE:

HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
            .path(TOKEN_ACCESS_PATH).build(getProperty("realm")));

List<NameValuePair> formParams = new ArrayList<NameValuePair>();

formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));

I am trying to do the same thing in axios.

AXIOS IMPLEMENTATION:

axios.post(authServerUrl +token_access_path,
        {
				username: 'abcd', //gave the values directly for testing
				password: '1235!',
				client_id: 'user-client'
		}).then(function(response) {
            console.log(response); //no output rendered
        }

Is the approach to set these form params on the post request correct?

Javascript Solutions


Solution 1 - Javascript

You have to do the following:

var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
    querystring.stringify({
            username: 'abcd', //gave the values directly for testing
            password: '1235!',
            client_id: 'user-client'
    }), {
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }).then(function(response) {
        console.log(response);
    });

Solution 2 - Javascript

If your target runtime supports it, Axios is able to accept a URLSearchParams instance which will also set the appropriate Content-type header to application/x-www-form-urlencoded

axios.post(authServerUrl + token_access_path, new URLSearchParams({
  username: 'abcd', //gave the values directly for testing
  password: '1235!',
  client_id: 'user-client'
}))

network console screenshot


The same goes for the fetch API

fetch(url, {
  method: "POST",
  body: new URLSearchParams({
    your: "object",
    props: "go here"
  })
})

Solution 3 - Javascript

Why pull in another library or module to do something so simple with pure vanilla JavaScript? It's really one line of JS to produce the desired data to submit in your POST request.

// es6 example

const params = {
  format: 'json',
  option: 'value'
};

const data = Object.keys(params)
  .map((key) => `${key}=${encodeURIComponent(params[key])}`)
  .join('&');

console.log(data);
// => format=json&option=value

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data,
  url: 'https://whatever.com/api',
};

const response = await axios(options);  // wrap in async function
console.log(response);

Solution 4 - Javascript

I agree with jhickok, no need to pull in an additional library however their code will not produce a correct result due to the usage of Object.entries, you would expect to see the following:

> "format,json=0&option,value=1"

Instead Object.keys should be used.

const obj = {
  format: 'json',
  option: 'value'
};

const data = Object.keys(obj)
  .map((key, index) => `${key}=${encodeURIComponent(obj[key])}`)
  .join('&');
  
console.log(data); // format=json&option=value

Then of course...

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data,
  url: 'https://whatever.com/api',
};

const response = await axios(options);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmmrajView Question on Stackoverflow
Solution 1 - JavascriptcperezView Answer on Stackoverflow
Solution 2 - JavascriptPhilView Answer on Stackoverflow
Solution 3 - JavascriptjhickokView Answer on Stackoverflow
Solution 4 - JavascriptNick HanshawView Answer on Stackoverflow