console.log('响应头:' + JSON.stringify(res.headers));
//头信息的名称为小写
let encoding = res.headers['content-encoding'];
//判断响应头中的内容编码,是否有过压缩,如果有则进行解压
if (encoding.match(/bgzipb/)) {
res.pipe(zlib.createGunzip()).pipe(process.stdout);
} else if (encoding.match(/bdeflateb/)) {
res.pipe(zlib.createInflate()).pipe(process.stdout);
} else {
res.pipe(process.stdout);
}
});
//请求过程中出错了触发
client.on('error', function (err) {
console.log(err);
});
//当 socket 被分配到请求后触发
client.on('socket', function (socket) {
socket.setTimeout(2 * 60 * 1000);
socket.on('timeout', function () {
//终止本次请求
client.abort()
});
});
也可以使用 http.get() 简便方法进行 get 请求。
const http = require('http');
//会自动调用 req.end(),默认为 get 请求。
http.get('http://www.baidu.com', function (res) {
res.on('data', function (data) {
console.log(data.toString());
});
});希望本文所述对大家node.js程序设计有所帮助。









