Http请求与节点?

如何使用与此代码等效的node.js创buildHttp请求:

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

       

网上收集的解决方案 "Http请求与节点?"

使用http客户端 。

沿着这些线路的东西:

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

对于其他人来说,这个问题被接受的答案是不正确的,并被弃用。

正确的方法(在撰写本文时)是使用http.request方法,如下所述: nodejitsu示例

代码示例(从上面的文章中,修改回答这个问题):

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