Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 921
Mark Avatar asked May 28 '11 00:05

Mark


People also ask

How HTTP POST request works in node js?

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header. We use Express. js in order to create a server and to make requests (GET, POST, etc).

How do I create an HTTP POST request in node js?

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.

How is an HTTP GET request made in node js?

It's called by creating an options object like: const options = { host: 'somesite.com', port: 443, path: '/some/path', method: 'GET', headers: { 'Content-Type': 'application/json' } }; And providing a callback function.

How does a HTTP POST request work?

In computing, POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accept the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form.


2 Answers

request is now deprecated. It is recommended you use an alternative

In no particular order and dreadfully incomplete:

  • native HTTP/S, const https = require('https');
  • node-fetch
  • axios
  • got
  • superagent
  • bent
  • make-fetch-happen
  • unfetch
  • tiny-json-http
  • needle
  • urllib

Stats comparision Some code examples

Original answer:

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

like image 156
Jed Watson Avatar answered Oct 22 '22 12:10

Jed Watson


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.

like image 22
onteria_ Avatar answered Oct 22 '22 13:10

onteria_