On
Post data using nodejs


This post highlights an attempt to handle the raw format of data sent in a POST request body and how one could parse it. There are packages like body-parser for Express that do this for us so this post is merely for learning purposes. I won’t suggest the use of this solution in production.

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);



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.

To install request use command npm install request

Example code:

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.