112

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?

5 Answers 5

170

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);
    });

Update: If you are using es6, change the import to import qs from 'qs';

Sign up to request clarification or add additional context in comments.

4 Comments

This helped me greatly, so simple querystring.stringify the json you want to send if your using application/x-www-form-urlencoded.
for es6 use import qs from 'qs'; to stringify your object
querystring is deprecated?
Its deprecated please update this
76

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"
  })
})

Comments

41

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

4 Comments

The is one step missing in your solution, encode the values. Replace de ${val} for ${encodeURIComponent(val)}
Thanks for the addition Giovane. I updated the code.
@Michael Cole why did you remove the square brackets destructure in your edit? They are necessary. The answer by Nick Hanshaw was presumably posted because of your change.
Indeed this edit was incorrect and not working. Edited according to Nick's working answer (probably this one was working before the false edit)
11

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

Comments

3
const body = new URLSearchParams();
body.append('param1', 'param1_value');
...
...
axios.post(url,body)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.