【问题标题】:Http request with node?带有节点的 Http 请求?
【发布时间】:2010-11-28 02:02:43
【问题描述】:

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

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

【问题讨论】:

    标签: javascript http node.js httpclient


    【解决方案1】:

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

    正确的方法(在撰写本文时)是使用 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();
    

    【讨论】:

    • 我不喜欢这个例子,因为它只是登录到控制台。有趣/困难的部分是处理响应字符串(异步)
    • 我不喜欢这个例子,因为它没有显示如何将 json 对象附加到消息正文
    • 嗯……我喜欢这个例子。将 console.log 更改为 response.write() 并不是那么难(或有趣)的家伙,并且 OP 没有询问任何关于附加 json 对象的问题,如果这个不符合您的需求,请提出您自己的问题跨度>
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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);
       });
      });
      

      【讨论】:

      • 任何人都知道如何处理超时。如果服务器在这种情况下没有响应?请评论。
      猜你喜欢
      • 2018-06-06
      • 2020-07-15
      • 2017-08-08
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多