简体   繁体   English

NodeJS请求模块 - http.IncomingMessage上的正文?

[英]NodeJS request module - body on http.IncomingMessage?

I'm looking into the node's request module, and documentation says that callback accepts three params - error , response ( http.IncomingMessage ) and body . 我正在查看节点的请求模块,文档说回调接受三个参数 - errorresponsehttp.IncomingMessage )和body

When making a request, I found that body also available as a property on the response object. 在发出请求时,我发现该主体也可用作response对象的属性。
Is that reliable? 这可靠吗? Can I just omit last param in the callback and use response.body instead? 我可以在回调中省略最后一个参数并使用response.body吗?

response.body is not always the same as the body argument. response.body并不总是与body参数相同。 If any processing is requested on the response such as decompression, then the body argument will be the result of that processing, but response.body may not reflect that processing. 如果对响应请求任何处理(例如解压缩),则body参数将是该处理的结果,但response.body可能不会反映该处理。 You should use the response argument. 您应该使用response参数。 Here's one example from the documentation: 以下是文档中的一个示例:

For backwards-compatibility, response compression is not supported by default. 为了向后兼容,默认情况下不支持响应压缩。 To accept gzip-compressed responses, set the gzip option to true. 要接受gzip压缩的响应,请将gzip选项设置为true。 Note that the body data passed through request is automatically decompressed while the response object is unmodified and will contain compressed data if the server sent a compressed response. 请注意,通过请求传递的正文数据会在响应对象未修改时自动解压缩,如果服务器发送压缩响应,则会包含压缩数据。

Yes, body is just a convenience for response.body so they are guaranteed to always be the same. 是的, body只是一个方便的response.body所以他们保证永远是相同的。

You can verify this by checking the source code . 您可以通过检查源代码来验证这一点。

self.emit('complete', response, response.body)

and elsewhere in the same file the complete event is handled 在同一文件中的其他地方处理complete事件

self.on('error', self.callback.bind())
self.on('complete', self.callback.bind(self, null))

This is only true of the response passed to the callback. 这仅适用于传递给回调的response The response object passed to the response event is a standard http.IncomingMessage and as such has no body property. 传递给响应事件response对象是标准的http.IncomingMessage ,因此没有body属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM