16

How do I make a Http request with node.js that is equivalent to this code:

curl -X PUT http://localhost:3000/users/1
700 Software
  • 85,281
  • 83
  • 234
  • 341
ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

35

For others googling this question, the accepted answer is no longer correct and has been deprecated.

The correct method (as of this writing) is to use the http.request method as described here: nodejitsu example

Code example (from the above article, modified to answer the question):

var http = require('http');

var options = {
  host: 'localhost',
  path: '/users/1',
  port: 3000,
  method: 'PUT'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();
Clayton Gulick
  • 9,755
  • 2
  • 36
  • 26
  • I don't like this example, as it's just logging to the console. The interesting/hard part though is to process the response string (asynchronously) – Sebastian Nov 22 '12 at 10:17
  • I dont like the example, as it doesnt show how to attach a json object to the message body – joshua Apr 14 '13 at 23:54
  • 13
    ummmm .... i like this example. changing console.log to response.write() isn't that hard (or interesting) guys, and the OP didn't ask anything about attaching a json object, ask your own question if this one doesn't fit your needs – Landon Apr 18 '13 at 22:48
22

Use the http client.

Something along these lines:

var http = require('http');
var client = http.createClient(3000, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
    // handle the response
});
MyGGaN
  • 1,766
  • 3
  • 30
  • 41
Swizec Teller
  • 2,322
  • 1
  • 19
  • 24
0
var http = require('http');
var client = http.createClient(1337, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
 });
});
Sarim
  • 3,124
  • 2
  • 20
  • 20
PTT
  • 526
  • 7
  • 27
  • any one have idea, how to handle timeout. If server is not responding in that case ? please comment. – maddy Apr 28 '15 at 10:12