节点http.request什么也不做
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; } } );
出于某种原因,这只是超时,不logging任何东西到控制台。
我知道我可以require('request')
但我需要使用http
来兼容我正在使用的插件。
另外,我的版本的背景:节点是v0.8.2
使用这里的例子: 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();
callback没有错误参数,你应该使用on(“错误”,…),你的请求不会被发送,直到你调用结束()
你准备了一个请求对象,但是没有用.end()来激活它。 (这个callback也不行。)
请参阅: http : //nodejs.org/api/http.html#http_event_request
这里夫妇的事情:
- 使用
hostname
不host
所以你是兼容url.parse()
( 见这里 ) - 请求的callback需要一个参数,它是一个
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();