节点http.request没有任何作用。

6
var http = require('http');

var options = {
    method: 'GET',
    host: 'www.google.com',
    port: 80,
    path: '/index.html'
};

http.request(
    options,
    function(err, resBody){
        console.log("hey");
        console.log(resBody);
        if (err) {
            console.log("YOYO");
            return;
        }
    }
);

由于某些原因,此代码会超时,并且不会在控制台中记录任何内容。

我知道我可以使用require('request'),但我需要使用http与我正在使用的插件兼容。

另外,请了解我的版本背景:Node 版本为 v0.8.2

3个回答

3
使用这里的示例:http://nodejs.org/api/http.html#http_http_request_options_callback
var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

回调函数没有错误参数,应该使用on("error", ...)。只有在调用end()方法后,您的请求才会被发送。

直到您调用end()之前,您的请求不会被发送。这不是真的,只是在那时才不会结束请求。尝试在没有结束请求的情况下写入请求并观察ngrep。请求会随着时间推移被发送并写入数据,TCP会话只有在调用.end()后才关闭。它之所以不起作用是因为没有向请求写入任何内容,并且它没有结束,因此节点正在等待知道要发送什么。 - Chad
确实,你是正确的。但是服务器会等待回复直到你调用end()或超时。 - Pascal Belloncle
1
根据响应类型,尝试使用不带结束的确切代码进行写入操作,并观察ngrep上发生的情况。 Google会立即响应,因为该URL不存在,您的应用程序将获取/解析错误响应然后退出。所有这些都在您从未调用end的情况下完成。我尝试了一下并观察了它的发生,因为我对假设持怀疑态度。我认为这是由于“GET”没有正文,因此如果您执行写入操作,则他们会认为您已经完成了。 - Chad
事实上,再仔细思考一下,这是一个非常有趣的数据点。感谢您进行实验! - Pascal Belloncle

3

0

有几个问题需要注意:

  • 请使用hostname而不是host,这样您就兼容了url.parse()请看这里
  • request的回调函数只需要一个参数,即http.ClientResponse
  • 要捕获错误,请使用req.on('error', ...)
  • 在使用http.request时,当你完成请求后,你需要结束请求req.end(),这样你才能写入任何需要的数据体(用req.write()),然后结束请求
    • 说明:http.get()将在底层为您执行此操作,这可能是您忘记的原因。

可行的代码:

var http = require('http');

var options = {
    method: 'GET',
    hostname: 'www.google.com',
    port: 80,
    path: '/index.html'
};

var req = http.request(
    options,
    function(res){
        console.log("hey");
        console.log(res);
    }
);

req.on('error', function(err) {
  console.log('problem', err);
});

req.end();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接