Mykola G. Mykola G. - 1 year ago 166
Node.js Question

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

I have code like following

var req = require('request');'someUrl',
{ form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'}, },
function (e, r, body) {

How can I set headers for this?
I need user-agent, content-type and probably smt else to be in 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 Source

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;

    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    uri: 'http://myUrl',
    body: formData,
    method: 'POST'
  }, function (err, res, body) {
    //it works!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download