Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 528
mmraj Avatar asked Jul 31 '15 23:07

mmraj


People also ask

How do I send body parameters in POST request Axios?

First we're passing the url of the service endpoint. Second we're passing object params which we created above and lastly we will pass headers to the post request. To pass raw data body content-type should be application/json.

How do I send a POST request from Axios?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios.

Does Axios encode urls?

By default, axios serializes JavaScript objects to JSON . To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

What does Axios post return?

The Axios response object consists of: data - the payload returned from the server. status - the HTTP code returned from the server. statusText - the HTTP status message returned by the server. headers - headers sent by server.


3 Answers

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);
    });
like image 183
cperez Avatar answered Oct 20 '22 15:10

cperez


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"
  })
})
like image 25
Phil Avatar answered Oct 20 '22 16:10

Phil


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);
like image 31
jhickok Avatar answered Oct 20 '22 15:10

jhickok