Http request with node?

2020-02-05 06:41发布

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

curl -X PUT http://localhost:3000/users/1

3条回答
三岁会撩人
2楼-- · 2020-02-05 07:10

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
});
查看更多
Fickle 薄情
3楼-- · 2020-02-05 07:18
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);
 });
});
查看更多
Juvenile、少年°
4楼-- · 2020-02-05 07:27

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();
查看更多
登录 后发表回答