Nodejs request 如何获取到带 http status 和 http headers 的 rawResponse,类似 curl -i --raw 的输出?
Nodejs request 如何获取到带 http status 和 http headers 的 rawResponse,类似 curl -i --raw 的输出?
是否有办法返回如下格式的文本?
# curl -i --raw https://httpbin.org/ip
HTTP/1.1 200 OK
Connection: keep-alive
Server: meinheld/0.6.1
Date: Wed, 30 Aug 2017 16:36:59 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Powered-By: Flask
X-Processed-Time: 0.000962972640991
Content-Length: 31
Via: 1.1 vegur
{
"origin": "11.52.71.4"
}
目前是使用
var headers = '';
for (var i = 0; i < rsp.rawHeaders.length; i++) {
headers += i % 2 ? (rsp.rawHeaders[i] + '\r\n') : (rsp.rawHeaders[i] + ': ');
}
console.log(‘HTTP/’ + rsp.httpVersion + ’ ’ + rsp.statusCode + ’ ’ + rsp.statusMessage
- ‘\r\n’ + headers + ‘\r\n’ + rsp.body);
pipe 到 buffer stream
我用下面 2 种方法获取到的都只有 response body,我用的方法和你说的不一样吗?还是我哪里用错了?javascript<br>const fs = require('fs');<br>const request = require('request');<br><br>var bufs = [];<br>request('<a target="_blank" href="https://httpbin.org/get'" rel="nofollow noopener">https://httpbin.org/get'</a>)<br> .on('data', function(d) {<br> bufs.push(d);<br> }).on('end', function() {<br> console.log(Buffer.concat(bufs).toString());<br> });<br><br>request('<a target="_blank" href="https://httpbin.org/get').pipe(fs.createWriteStream('/tmp/response.raw'));" rel="nofollow noopener">https://httpbin.org/get').pipe(fs.createWriteStream('/tmp/response.raw'));</a><br><br>request('<a target="_blank" href="https://httpbin.org/get'" rel="nofollow noopener">https://httpbin.org/get'</a>, function(err, rsp, body) {<br> // 上面 2 种方法获取到的数据就是 body 的数据<br> console.log(body);<br>});<br>