99

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?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
mmraj
  • 1,875
  • 4
  • 16
  • 19

5 Answers5

163

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);
    });
cperez
  • 1,646
  • 1
  • 11
  • 3
63

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"
  })
})
Phil
  • 157,677
  • 23
  • 242
  • 245
36

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);
Blacklight
  • 3,809
  • 2
  • 33
  • 39
jhickok
  • 908
  • 9
  • 11
  • 5
    The is one step missing in your solution, encode the values. Replace de `${val}` for `${encodeURIComponent(val)}` – Giovane May 02 '19 at 17:11
  • 2
    Thanks for the addition Giovane. I updated the code. – jhickok May 13 '19 at 14:31
  • @Michael Cole why did you remove the square brackets destructure in your edit? They are necessary. The [answer by Nick Hanshaw](https://stackoverflow.com/a/66294282/135101) was presumably posted because of your change. – Tyler Collier Feb 24 '21 at 04:47
  • Indeed this edit was incorrect and not working. Edited according to Nick's working answer (probably this one was working before the false edit) – Blacklight Feb 26 '21 at 14:41
9

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);
Nick Hanshaw
  • 376
  • 4
  • 7
2
const body = new URLSearchParams();
body.append('param1', 'param1_value');
...
...
axios.post(url,body)