How is an HTTP POST request made in node.js?


How can I make an outbound HTTP POST request, with data, in node.js?

3/5/2019 2:35:51 AM

Accepted Answer

Here's an example of using node.js to make a POST request to the Google Compiler API:

// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');

function PostCode(codestring) {
  // Build the post string from an object
  var post_data = querystring.stringify({
      'compilation_level' : 'ADVANCED_OPTIMIZATIONS',
      'output_format': 'json',
      'output_info': 'compiled_code',
        'warning_level' : 'QUIET',
        'js_code' : codestring

  // An object of options to indicate where to post to
  var post_options = {
      host: '',
      port: '80',
      path: '/compile',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);

  // post the data


// This is an async file read
fs.readFile('LinkedList.js', 'utf-8', function (err, data) {
  if (err) {
    // If this were just a small part of the application, you would
    // want to handle this differently, maybe throwing an exception
    // for the caller to handle. Since the file is absolutely essential
    // to the program's functionality, we're going to exit with a fatal
    // error instead.
    console.log("FATAL An error occurred trying to read in the file: " + err);
  // Make sure there's data before we post it
  if(data) {
  else {
    console.log("No data to post");

I've updated the code to show how to post data from a file, instead of the hardcoded string. It uses the async fs.readFile command to achieve this, posting the actual code after a successful read. If there's an error, it is thrown, and if there's no data the process exits with a negative value to indicate failure.

10/28/2015 12:26:28 PM

This gets a lot easier if you use the request library.

var request = require('request');
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {

Aside from providing a nice syntax it makes json requests easy, handles oauth signing (for twitter, etc.), can do multi-part forms (e.g. for uploading files) and streaming.

To install request use command npm install request

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow