我在节点中尝试http.request
。但我的测试脚本永远不会完成。
THX!
const http = require('http');
const parse_url = require('url').parse;
const srv = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
srv.listen(0);
const addr = srv.address();
const url = `http://localhost:${addr.port}`;
const url_obj = parse_url(url);
const option = {
protocol: url_obj.protocol,
host: url_obj.host,
hostname: url_obj.hostname,
port: addr.port,
path: '/',
method: 'GET'
};
console.log(option);
const req = http.request(option, (res) => {
console.log('done');
srv.close();
});
// below is only for debugging
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.on('socket', (socket) => {
console.log('socket event');
socket.on('data', function() {
console.log('data', arguments);
});
socket.on('lookup', function() {
console.log('lookup', arguments);
});
socket.on('end', function() {
console.log('end', arguments);
});
});
这是控制台输出:
$ node t.js
{ protocol: 'http:',
host: 'localhost:43347',
hostname: 'localhost',
port: 43347,
path: '/',
method: 'GET' }
socket event
lookup { '0': null, '1': '127.0.0.1', '2': 4, '3': 'localhost' }
脚本永远不会退出。理想情况下,它应该在srv.close()
答案 0 :(得分:1)
我在文件中错过了这句话
请注意,在示例中调用了req.end()。用http.request()一个 必须始终调用req.end()来表示您已经完成了 请求 - 即使没有数据写入请求正文。
https://nodejs.org/api/http.html#http_http_request_options_callback