nodejs http.get 响应中的 body 在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6968448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where is body in a nodejs http.get response?
提问by mikemaccana
I'm reading the docs at http://nodejs.org/docs/v0.4.0/api/http.html#http.request, but for some reason, I can't seem to to actually find the body/data attribute on the returned, finished response object.
我正在阅读http://nodejs.org/docs/v0.4.0/api/http.html#http.request 上的文档,但由于某种原因,我似乎无法真正找到 body/data 属性在返回的、完成的响应对象上。
> var res = http.get({host:'www.somesite.com', path:'/'})
> res.finished
true
> res._hasBody
true
It's finished (http.get does that for you), so it should have some kind of content. But there's no body, no data, and I can't read from it. Where is the body hiding?
它已经完成了(http.get 为你做的),所以它应该有某种内容。但是没有实体,没有数据,我无法从中读取。尸体藏在哪里?
采纳答案by mikemaccana
Edit: replying to self 6 years later
编辑:6年后回复自己
The awaitkeywordis the best way to handle this, avoiding callbacks and .then()
该的await关键字是处理最好的办法,避免了回调和.then()
You'll also need to use an HTTP client that returns Promises.http.get()still returns a Request object, so that won't work. You could use fetch, but superagentis a mature HTTP client which features more reasonable defaults including simpler query string encoding, properly using mime types, JSON by default, and other common HTTP client features. awaitwill wait until the Promise has a value - in this case, an HTTP reponse!
您还需要使用返回 Promise 的 HTTP 客户端。http.get()仍然返回一个 Request 对象,所以这不起作用。您可以使用fetch, 但它superagent是一个成熟的 HTTP 客户端,它具有更合理的默认设置,包括更简单的查询字符串编码、正确使用 mime 类型、默认 JSON 以及其他常见的 HTTP 客户端功能。await将等到 Promise 具有值 - 在这种情况下,是 HTTP 响应!
const superagent = require('superagent');
(async function(){
const response = await superagent.get('https://www.google.com')
console.log(response.text)
})();
Using await, control simply passes onto the next lineonce the promise returned by superagent.get()has a value.
使用await,一旦返回的promise有一个值,控制就会简单地传递到下一行superagent.get()。
回答by yojimbo87
http.requestdocs contains example how to receive body of the response through handling dataevent:
http.request文档包含如何通过处理data事件接收响应正文的示例:
var options = {
host: '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();
http.getdoes the same thing as http.request except it calls req.end()automatically.
http.get与http.request做同样的事情,除了它会req.end()自动调用。
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
回答by bizi
I also want to add that the http.ClientResponsereturned by http.get()has an endevent, so here is another way that I receive the body response:
我还想补充一点,http.ClientResponse返回的 byhttp.get()有一个end事件,所以这是我接收正文响应的另一种方式:
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
console.log(body);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
回答by nkron
The dataevent is fired multiple times with 'chunks' of the body as they are downloaded and an endevent when all chunks have been downloaded.
该data事件在下载end时使用主体的“块”多次触发,并在下载所有块时触发。
With Node supporting Promisesnow, I created a simple wrapper to return the concatenated chunks through a Promise:
现在 Node 支持Promises,我创建了一个简单的包装器来通过 Promise 返回连接的块:
const httpGet = url => {
return new Promise((resolve, reject) => {
http.get(url, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => resolve(body));
}).on('error', reject);
});
};
You can call it from an async function with:
您可以从异步函数调用它:
const body = await httpGet('http://www.somesite.com');
回答by user969714
If you want to use .get you can do it like this
如果你想使用 .get 你可以这样做
http.get(url, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log(chunk);
});
});
回答by Skomski
You need to add a listener to the request because node.js works asynchronous like that:
您需要向请求添加一个侦听器,因为 node.js 像这样异步工作:
request.on('response', function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
回答by Thulasiram
Needle module is also good, here is an example which uses needlemodule
针模块也不错,这里是一个使用needle模块的例子
var needle = require('needle');
needle.get('http://www.google.com', function(error, response) {
if (!error && response.statusCode == 200)
console.log(response.body);
});
回答by Vince
You can't get the body of the response from the return value of http.get().
您无法从 的返回值中获取响应的正文http.get()。
http.get()doesn't return a response object. It returns the request object (http.clientRequest). So, there isn't any way to get the body of the response from the return value of http.get().
http.get()不返回响应对象。它返回请求对象 ( http.clientRequest)。因此,没有任何方法可以从http.get().
I know it's an old question, but reading the documentation you linked toshows that this was the case even when you posted it.
我知道这是一个老问题,但是阅读您链接到的文档表明即使您发布它也是如此。
回答by 18augst
A portion of Coffee here:
这里有一部分咖啡:
# My little helper
read_buffer = (buffer, callback) ->
data = ''
buffer.on 'readable', -> data += buffer.read().toString()
buffer.on 'end', -> callback data
# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
read_buffer res, (response) ->
# Do some things with your response
# but don't do that exactly :D
eval(CoffeeScript.compile response, bare: true)
And compiled
并编译
var read_buffer;
read_buffer = function(buffer, callback) {
var data;
data = '';
buffer.on('readable', function() {
return data += buffer.read().toString();
});
return buffer.on('end', function() {
return callback(data);
});
};
http.get('http://i.want.some/stuff', function(res) {
return read_buffer(res, function(response) {
return eval(CoffeeScript.compile(response, {
bare: true
}));
});
});

