Node.js: How to send headers with form data using request module?

Mike G. picture Mike G. · Jun 15, 2013 · Viewed 207.5k times · Source

I have code like the following:

var req = require('request');

req.post('someUrl',
   { form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'}, },
   function (e, r, body) {
      console.log(body);
});

How can I set headers for this? I need user-agent, content-type and probably something else to be in the headers:

headers = { 
   'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
   'Content-Type' : 'application/x-www-form-urlencoded' 
};

I've tried in multiple ways but I can either send header or form-data, failed to send both.

Answer

Mike G. picture Mike G. · Jul 9, 2014

I've finally managed to do it. Answer in code snippet below:

var querystring = require('querystring');
var request = require('request');

var form = {
    username: 'usr',
    password: 'pwd',
    opaque: 'opaque',
    logintype: '1'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'http://myUrl',
    body: formData,
    method: 'POST'
  }, function (err, res, body) {
    //it works!
  });