nodejs http.get 响应中的 body 在哪里? [英] Where is body in a nodejs http.get response?
问题描述
我正在阅读 http://nodejs 上的文档.org/docs/v0.4.0/api/http.html#http.request,但由于某种原因,我似乎无法在返回的已完成响应对象上实际找到 body/data 属性.
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.
> var res = http.get({host:'www.somesite.com', path:'/'})
> res.finished
true
> res._hasBody
true
它已经完成了(http.get 为你做的),所以它应该有一些内容.但是没有实体,没有数据,我无法从中读取.尸体藏在哪里?
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?
推荐答案
6年后回复自己
await 关键字 是从 HTTP 请求获得响应的最佳方式,避免回调和 .then()
您还需要使用返回 Promises 的 HTTP 客户端. http.get()
仍然返回一个 Request 对象,因此它不起作用.
You'll also need to use an HTTP client that returns Promises. http.get()
still returns a Request object, so that won't work.
fetch
是一个低级客户端,它既可以从 npm 获得,也可以在以后的 node 版本中使用superagent
是一个成熟的 HTTP 客户端,具有更合理的默认设置,包括更简单的查询字符串编码、正确使用 mime 类型、默认 JSON 以及其他常见的 HTTP 客户端功能.axios
也很流行,和superagent
有类似的优势
fetch
is a low level client, that is both available from npm and will be in future versions of nodesuperagent
is a mature HTTP clients that features more reasonable defaults including simpler query string encoding, properly using mime types, JSON by default, and other common HTTP client features.axios
is also quite popular and has similar advantages tosuperagent
await
将等到 Promise 具有值 - 在本例中为 HTTP 响应!
await
will wait until the Promise has a value - in this case, an HTTP response!
const superagent = require('superagent');
(async function(){
const response = await superagent.get('https://www.google.com')
console.log(response.text)
})();
使用 await,一旦 superagent.get()
返回的承诺有值,控制只需传递到下一行.
Using await, control simply passes onto the next line once the promise returned by superagent.get()
has a value.
这篇关于nodejs http.get 响应中的 body 在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!