2013-02-12 72 views
4
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; 
     } 
    } 
); 

由于某些原因,这只是超时,并没有记录任何东西到控制台。节点http.request不做任何事

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

此外,背景在我的版本:节点是v0.8.2

回答

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

回调没有错误的参数,你应该使用的( “错误”,...) 和你的请求不被发送,直到你调用结束()

+0

'你的请求不被发送,直到你调用结束()'不正确的,它只是不_END_的请求,直到然后。尝试写入请求,不要结束并观看'ngrep'。发送请求并随时间将数据写入请求,直到调用'.end()',TCP会话才会关闭。他没有做任何事情的原因是因为没有任何内容写入请求,并且它没有结束,所以节点正在等待知道要发送什么。 – Chad 2013-02-12 22:52:54

+0

确实,你是对的。但服务器将等待回复,直到您调用end()或超时。 – 2013-02-12 22:54:35

+1

取决于响应类型,尝试用他的确切代码写一段没有结束的内容,并观察ngrep上发生了什么。谷歌立即响应,因为该URL不存在,你的应用程序将得到/解析错误响应,然后退出。所有没有你永远打电话结束。我试了一下,看着它发生,因为我怀疑这个假设。我认为这是因为'GET'没有身体,所以如果你打了一个字,他们认为你已经完成了。 – Chad 2013-02-13 01:47:03

0

夫妇这边的事情:

  • 使用hostnamehost所以你可以兼容url.parse()see here
  • 的请求回调需要一个参数,它是一个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();