带节点的Http请求?

时间:2010-11-28 02:02:44

标签: javascript http node.js httpclient

如何使用与此代码等效的node.js发出Http请求:

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

3 个答案:

答案 0 :(得分:35)

对于搜索此问题的其他人,已接受的答案已不再正确,已被弃用。

正确的方法(截至撰写本文时)是使用此处所述的http.request方法:nodejitsu example

代码示例(来自上面的文章,修改为回答问题):

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();

答案 1 :(得分:22)

使用http client

这些方面的东西:

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
});

答案 2 :(得分: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);
 });
});
相关问题