Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http request with node?

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

curl -X PUT http://localhost:3000/users/1
like image 500
ajsie Avatar asked Nov 28 '10 02:11

ajsie


2 Answers

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();
like image 125
Clayton Gulick Avatar answered Oct 07 '22 04:10

Clayton Gulick


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
});
like image 35
Swizec Teller Avatar answered Oct 07 '22 05:10

Swizec Teller