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

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.

This question is related to node.js header request form-data

The answer is


Just remember set method to POST in options. Here is my code

var options = {
    url: 'http://www.example.com',
    method: 'POST', // Don't forget this line
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    },
    form: {
        'key-1':'value-1',
        'key-2':'value-2',
        ...
    }
};

//console.log('options:', options);

// Create request to get data
request(options, (err, response, body) => {
    if (err) {
        //console.log(err);
    } else {
        console.log('body:', body);
    }
});

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.

You should add method: 'POST' and your code will work if your backend receive the post method.

var req = require('request');

req.post({
   url: 'someUrl',
   form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
   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' 
   },
   method: 'POST'
  },

  function (e, r, body) {
      console.log(body);
  });

I found the solution of this problem and i should work i'm sure about this because i also face the same problem

here is my solution----->

var request = require('request');

//set url
var url = 'http://localhost:8088/example';

//set header
var headers = {
    'Authorization': 'Your authorization'
};

//set form data
var form = {first_name: first_name, last_name: last_name};

//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {

    var bodyValues = JSON.parse(body);
    res.send(bodyValues);
});

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean` No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll

Examples related to request

How to send Basic Auth with axios How to post raw body data with curl? Pandas read_csv from url POST request with a simple string in body with Alamofire PHP GuzzleHttp. How to make a post request with params? How to modify the nodejs request default timeout time? Doing HTTP requests FROM Laravel to an external API CORS jQuery AJAX request Node.js request CERT_HAS_EXPIRED What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Examples related to form-data

How to convert FormData (HTML5 object) to JSON Send FormData with other field in AngularJS Convert JS Object to form data Send FormData and String Data Together Through JQuery AJAX? How to add header data in XMLHttpRequest when using formdata? Node.js: How to send headers with form data using request module? How to inspect FormData? appending array to FormData and send via AJAX FormData.append("key", "value") is not working How to give a Blob uploaded as FormData a file name?