Home > database >  How to understand request object?
How to understand request object?

Time:07-16

In my expresjs code, if I print an incoming request from app.js...

app.use(function (req, res, next) {
    console.log(req);
    ...

I can see some headers that I expect, such as

url: '/'
method: 'GET'

But there are a surprising number of others included, such as

_readableState:
_events:
socket:

In mdn these do not appear in the list of http headers. Nor do they appear in Request interface properties.

Then what am I looking at? Can someone please point me towards a resource to help me understand what these values are used for?

CodePudding user response:

The request object is an Express-customized version of http.IncomingMessage as described in the nodejs doc here.

At it's core, it is a combination of properties from the incoming request (such as incoming headers) and a stream.readable that represents the incoming data from the http request.

If the request is a GET, then there is typically no body to that request and the headers of the request have already been read from the incoming stream (by the underlying http library) and parsed and are stored in the req object as properties that you can read about here in the Express doc and here in the http library doc.

If the request is something with a body such as a PUT or POST, then the req object represents the TCP stream where the body data can be read from either by your custom request handler or by middleware such as express.json() or multer or other middleware designed to handle specific types of http bodies.

Properties such as _readableState are part of the incoming stream in req.

Properties such as method are part of the http.incomingMessage in req.

Properties such as socket are the underlying TCP socket that the http request arrived on and is used by the stream to read the body from the stream and to close the request when done reading.

req is essentially a blend or mixin of several classes giving it these various behaviors all in one object.

  • Related