Rectangle 27 620

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: 'closure-compiler.appspot.com',
      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.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

// 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);
    process.exit(-2);
  }
  // Make sure there's data before we post it
  if(data) {
    PostCode(data);
  }
  else {
    console.log("No data to post");
    process.exit(-1);
  }
});

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.

querystring.stringify()
qs.stringify()

Content-Length is bytes and not necessarily string length (UTF-16 etc). Using Buffer.byteLength(data) will always be correct.

for sending standard postdata, the object in querystring.stringify should be your own data object, not the junk that is displayed in this answer (which may be useful for file based objects?). I was stuck on that for ages... stackoverflow.com/questions/9768192/ provided my complete solution

Gotcha: If you are using an ssl-encrypted site, you will need the "https" library. You can't just change the port to 443.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 619

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: 'closure-compiler.appspot.com',
      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.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

// 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);
    process.exit(-2);
  }
  // Make sure there's data before we post it
  if(data) {
    PostCode(data);
  }
  else {
    console.log("No data to post");
    process.exit(-1);
  }
});

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.

querystring.stringify()
qs.stringify()

Content-Length is bytes and not necessarily string length (UTF-16 etc). Using Buffer.byteLength(data) will always be correct.

for sending standard postdata, the object in querystring.stringify should be your own data object, not the junk that is displayed in this answer (which may be useful for file based objects?). I was stuck on that for ages... stackoverflow.com/questions/9768192/ provided my complete solution

Gotcha: If you are using an ssl-encrypted site, you will need the "https" library. You can't just change the port to 443.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 796

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

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);

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.

npm install request

My program doesn't actually send the http request post when I keep the function handling errors. Once I deleted it, it worked. Your link also doesn't include the error handling. Perhaps this is the newest version.

{ form: { key: 'value' } } should be replaced by { json: { key: 'value' } } (as the question is not specific to forms). One also have to understand 'form' and 'json' are request library keywords and not part of the custom data (as trivial as this last comment could appear, it took me some time to figure it...)

You deserve a golden badge purely for this answer. It's so much more useful than the accepted one...and it already existed back in 2012? Wow

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 793

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

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);

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.

npm install request

My program doesn't actually send the http request post when I keep the function handling errors. Once I deleted it, it worked. Your link also doesn't include the error handling. Perhaps this is the newest version.

{ form: { key: 'value' } } should be replaced by { json: { key: 'value' } } (as the question is not specific to forms). One also have to understand 'form' and 'json' are request library keywords and not part of the custom data (as trivial as this last comment could appear, it took me some time to figure it...)

You deserve a golden badge purely for this answer. It's so much more useful than the accepted one...and it already existed back in 2012? Wow

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 79

var request = require('request');
var myJSONObject = { ... };
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJSONObject
}, function (error, response, body){
    console.log(response);
});
var myXMLText = '<xml>...........</xml>'
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
}, function (error, response, body){
    console.log(response);
});

After review in their documentation. it states the following: json - sets body but to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON. That means when json = true, it will set header and json and body. Otherwise, no header set, and parse as text. (Like the above XML example). That makes the request API handy and simplistic but quite hard to understand at first time.

It is technically in their docs, but none of the examples show it--only form data. It's a needle in the haystack, and as such, it's a huge ommission, since this is the second most frequent way I use ajax in JS, ever, and certainly one of the most common on the web.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 79

var request = require('request');
var myJSONObject = { ... };
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJSONObject
}, function (error, response, body){
    console.log(response);
});
var myXMLText = '<xml>...........</xml>'
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
}, function (error, response, body){
    console.log(response);
});

After review in their documentation. it states the following: json - sets body but to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON. That means when json = true, it will set header and json and body. Otherwise, no header set, and parse as text. (Like the above XML example). That makes the request API handy and simplistic but quite hard to understand at first time.

It is technically in their docs, but none of the examples show it--only form data. It's a needle in the haystack, and as such, it's a huge ommission, since this is the second most frequent way I use ajax in JS, ever, and certainly one of the most common on the web.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 37

I use Restler and Needle for production purposes. They are both much more powerful than native httprequest. It is possible to request with basic authentication, special header entry or even upload/download files.

As for post/get operation, they also are much simpler to use than raw ajax calls using httprequest.

needle.post('https://my.app.com/endpoint', {foo:'bar'}, 
    function(err, resp, body){
        console.log(body);
});

I tried request, node-form-data and superagent before needle. needle was the only one that worked correctly for me when trying to do a multipart form file upload.

Needle is an excellent tool that makes REST calls a lot simpler!

Thanks, I've been looking for something like needle for a while (an alternative to the request library, which is a bloated, horribly-written mess). I was about to write my own but now I don't need to.

Thanks for that. The request library was given a connection reset for me. Needle works like a charm.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 37

I use Restler and Needle for production purposes. They are both much more powerful than native httprequest. It is possible to request with basic authentication, special header entry or even upload/download files.

As for post/get operation, they also are much simpler to use than raw ajax calls using httprequest.

needle.post('https://my.app.com/endpoint', {foo:'bar'}, 
    function(err, resp, body){
        console.log(body);
});

I tried request, node-form-data and superagent before needle. needle was the only one that worked correctly for me when trying to do a multipart form file upload.

Needle is an excellent tool that makes REST calls a lot simpler!

Thanks, I've been looking for something like needle for a while (an alternative to the request library, which is a bloated, horribly-written mess). I was about to write my own but now I don't need to.

Thanks for that. The request library was given a connection reset for me. Needle works like a charm.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 12

$ npm install request
var request = require('request')

var options = {
  method: 'post',
  body: postData, // Javascript object
  json: true, // Use,If you are sending JSON data
  url: url,
  headers: {
    // Specify headers, If any
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log('Error :', err)
    return
  }
  console.log(' Body :', body)

});

You can also use Node.js's built-in 'http' module to make request.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 12

$ npm install request
var request = require('request')

var options = {
  method: 'post',
  body: postData, // Javascript object
  json: true, // Use,If you are sending JSON data
  url: url,
  headers: {
    // Specify headers, If any
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log('Error :', err)
    return
  }
  console.log(' Body :', body)

});

You can also use Node.js's built-in 'http' module to make request.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 19

You can also use Requestify, a really cool and simple HTTP client I wrote for nodeJS + it supports caching.

var requestify = require('requestify');

    requestify.post('http://example.com', {
        hello: 'world'
    })
    .then(function(response) {
        // Get the response body (JSON parsed or jQuery object for XMLs)
        response.getBody();
    });

Thanks for the feedback and bug reporting, it was fixed and deployed quickly (-:

@RyanDawkins - "a really cool and simple HTTP client I wrote"

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 19

You can also use Requestify, a really cool and simple HTTP client I wrote for nodeJS + it supports caching.

var requestify = require('requestify');

    requestify.post('http://example.com', {
        hello: 'world'
    })
    .then(function(response) {
        // Get the response body (JSON parsed or jQuery object for XMLs)
        response.getBody();
    });

Thanks for the feedback and bug reporting, it was fixed and deployed quickly (-:

@RyanDawkins - "a really cool and simple HTTP client I wrote"

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 4

In the options object you include the request options as you did in the GET request and you create one more object containing the data you want in your POST's body. You stringify that using the querystring function (which you need to install by npm install querystring) and then you forward it by using the write() and end() methods of https.request().

It is important to note that you need two extra headers in your options object in order to make a successful post request. These are :

'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length

so you probably need to init your options object after querystring.stringify has returned. Otherwise you won't know the length of the stringified body data.

var querystring = require('querystring')
var https = require('https')


postData = {   //the POST request's body data
   type: deviceType,
   id: deviceId,
   metadata: {
      address: {
         number: deviceNumber,
         street: deviceStreet
      }
   }            
};

postBody = querystring.stringify(postData);
//init your options object after you call querystring.stringify because you  need
// the return string for the 'content length' header

options = {
   //your options which have to include the two headers
   headers : {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': postBody.length
   }
};


var postreq = https.request(options, function (res) {
        //Handle the response
});
postreq.write(postBody);
postreq.end();

javascript - Node.js https.post request - Stack Overflow

javascript node.js http post request
Rectangle 27 16

For those coming here in the later years. There are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.

npm
$ npm install unirest

And onto the Hello, World! example that everyone is accustomed to.

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
  console.log(response.body);
});

Extra: A lot of people are also suggesting the use of request [ 2 ]

It should be worth noting that behind the scenes Unirest uses the request library.

var Request = unirest.get('http://mockbin.com/request');

Another one I found that looks pretty good is github.com/request/request which seems a bit more popular than unirest at least as of this writing

I can attest to request. It is a very good library. I find that request provides more low level functionality so it's appropriate to use it for specific applications. When I don't necessarily care about the low level stuff, I find Unirest to be adequate.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 16

For those coming here in the later years. There are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.

npm
$ npm install unirest

And onto the Hello, World! example that everyone is accustomed to.

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
  console.log(response.body);
});

Extra: A lot of people are also suggesting the use of request [ 2 ]

It should be worth noting that behind the scenes Unirest uses the request library.

var Request = unirest.get('http://mockbin.com/request');

Another one I found that looks pretty good is github.com/request/request which seems a bit more popular than unirest at least as of this writing

I can attest to request. It is a very good library. I find that request provides more low level functionality so it's appropriate to use it for specific applications. When I don't necessarily care about the low level stuff, I find Unirest to be adequate.

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 4

In the options object you include the request options as you did in the GET request and you create one more object containing the data you want in your POST's body. You stringify that using the querystring function (which you need to install by npm install querystring) and then you forward it by using the write() and end() methods of https.request().

It is important to note that you need two extra headers in your options object in order to make a successful post request. These are :

'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length

so you probably need to init your options object after querystring.stringify has returned. Otherwise you won't know the length of the stringified body data.

var querystring = require('querystring')
var https = require('https')


postData = {   //the POST request's body data
   type: deviceType,
   id: deviceId,
   metadata: {
      address: {
         number: deviceNumber,
         street: deviceStreet
      }
   }            
};

postBody = querystring.stringify(postData);
//init your options object after you call querystring.stringify because you  need
// the return string for the 'content length' header

options = {
   //your options which have to include the two headers
   headers : {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': postBody.length
   }
};


var postreq = https.request(options, function (res) {
        //Handle the response
});
postreq.write(postBody);
postreq.end();

javascript - Node.js https.post request - Stack Overflow

javascript node.js http post request
Rectangle 27 6

To Post Rest/JSON Request We can simply use request package and save the values we have to send in Json variable.

First install the require package in your console by npm install request --save

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest
Rectangle 27 6

To Post Rest/JSON Request We can simply use request package and save the values we have to send in Json variable.

First install the require package in your console by npm install request --save

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

How to make an HTTP POST request in node.js? - Stack Overflow

node.js http post httprequest