How to make an HTTP post request in node.js

According to nodejs.org, Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Not sure about using Node.js for your own project? It is currently being used at such places as Microsoft, Yahoo, PayPal, LinkedIn, and Groupon, just to name a few.

Note: The recipe assumes you have Node.js installed on your local system. If you do not have it installed yet, you'll need to go to http://www.nodejs.org/ first and install it.

DIFFICULTY Basic - 1 | Medium - 2 | Advanced - 3
TIME REQUIRED 20 min
RELATED PRODUCTS Linux-based VPS or dedicated servers

To test the execution of a Node.js program that wants to do an HTTP POST command to a server, you need an actual server to capture the command. http://postcatcher.in/ offers one such free test server. Before getting started, you'll need to do some preliminary setup there. First, go to the site in your browser:

http://postcatcher.in

and click Start testing your POST requests now.

This will bring up a new page with a hex number that looks like 544b09b4599c1d0200000289. Be prepared to copy that into the source you'll be creating next.

Next, create a file named post.js in your favorite text editor and place the following program:

var http = require("http");
var options = {
  hostname: 'www.postcatcher.in',
  port: 80,
  path: '/catchers/544b09b4599c1d0200000289',
  method: 'POST',
  headers: {
      'Content-Type': 'application/json',
  }
};
var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": "Hello, World"}');
req.end();

You'll need to make sure the number string 544b09b4599c1d0200000289 in the path above is replaced with YOUR string. The options variable in the source above describes where to send the request. The http.request() call is what does the actual request. Since method: 'POST' is defined in the options, a POST request is done.

To run the program, just pass the name of the newly created file to the node command:

node post.js

If you go back to the postcatcher.in site, you'll see that it shows the body of the request sent, the req.write() contents.


Помогла ли вам эта статья?
Благодарим вас за отзыв. Чтобы связаться с сотрудником службы поддержки клиентов, позвоните по номеру этой службы или воспользуйтесь опцией чата выше.
Мы рады вам помочь! У вас остались вопросы?
Приносим извинения. Расскажите нам, какие затруднения вы испытываете или почему рекомендованное решение не помогло устранить проблему.