是否有办法返回如下格式的文本?
# 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);
1
vietor 2017-08-31 08:13:30 +08:00 via Android
pipe 到 buffer stream
|
2
fuxkcsdn OP @vietor 我用下面 2 种方法获取到的都只有 response body,我用的方法和你说的不一样吗?还是我哪里用错了?
```javascript const fs = require('fs'); const request = require('request'); var bufs = []; request('https://httpbin.org/get') .on('data', function(d) { bufs.push(d); }).on('end', function() { console.log(Buffer.concat(bufs).toString()); }); request('https://httpbin.org/get').pipe(fs.createWriteStream('/tmp/response.raw')); request('https://httpbin.org/get', function(err, rsp, body) { // 上面 2 种方法获取到的数据就是 body 的数据 console.log(body); }); ``` |