Search code examples
node.jsrestrequest

how to post data in node.js with content type ='application/x-www-form-urlencoded'


I'm having a problem in posting data in node.js with Content-type: 'application/x-www-form-urlencoded'

var loginArgs = {
    data: 'username="xyzzzzz"&"password="abc12345#"',

    //data: {
    //    'username': "xyzzzzz",
    //    'password': "abc12345#",
    //},

    headers: {
            'User-Agent': 'MYAPI',
            'Accept': 'application/json',
            'Content-Type':'application/x-www-form-urlencoded'      
    }   
};

And post request is:

client.post("http:/url/rest/login", loginArgs, function(data, response){
console.log(loginArgs);

if (response.statusCode == 200) {
    console.log('succesfully logged in, session:', data.msg);
}

It always returns username/password incorrect.

In the rest api it is said that the request body should be:

username='provide user name in url encoded
format'&password= "provide password in url encoded format'

Solution

  • request supports application/x-www-form-urlencoded and multipart/form-data form uploads. For multipart/related refer to the multipart API.

    application/x-www-form-urlencoded (URL-Encoded Forms)

    URL-encoded forms are simple:

    const request = require('request');
    
    request.post('http:/url/rest/login', {
      form: {
        username: 'xyzzzzz',
        password: 'abc12345#'
      }
    })
    // or
    request.post('http:/url/rest/login').form({
      username: 'xyzzzzz',
      password: 'abc12345#'
    })
    // or
    request.post({
      url: 'http:/url/rest/login',
      form: {
        username: 'xyzzzzz',
        password: 'abc12345#'
      }
    }, function (err, httpResponse, body) { /* ... */ })
    

    See: https://github.com/request/request#forms

    Or, using request-promise

    const rp = require('request-promise');
    rp.post('http:/url/rest/login', {
      form: {
        username: 'xyzzzzz',
        password: 'abc12345#'
      }
    }).then(...);
    

    See: https://github.com/request/request-promise#api-in-detail