I'm looking into the node's request module, and documentation says that callback accepts three params - error
, response
( http.IncomingMessage
) and body
.
When making a request, I found that body also available as a property on the response
object.
Is that reliable? Can I just omit last param in the callback and use response.body
instead?
response.body
is not always the same as the body
argument. 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. You should use the response
argument. 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. 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.
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
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. The response
object passed to the response event is a standard http.IncomingMessage
and as such has no body
property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.