1

It seems like from a conceptual perspective the request is what is propogating through the middle ware until it reaches the final middleware (which is named after the request type: app.get, app.post) then the request is terminated and the response begins inside of the final middleware.

NOW the response object is created...and includes any response variables and the view?

Does the request end at the apps entry point or at the final middleware?

Are we building the response object or the request object in the intermediate middlewares?

Or are they both passed through in parallel and it really doesn't matter?

Here's a similar question but doesn't answer it to my satisfaction.

req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware

Community
  • 1
  • 1
Dr. Chocolate
  • 2,043
  • 4
  • 25
  • 45

1 Answers1

1

They should just be let through. It's one of those black magic things where without deep digging you might never be sure.

The essential thing here is that since it's JavaScript, the req and res from (req, res, next) arguments are actually references to the underlying objects. Therefore if you did req = null, it would only lose the reference, not the underlying object. I think that express keeps the references in its stack and then invokes the middlewares with them. If that is the case, then all that's happening is that (from http server) the req and res exist from the beginning. So if you wanted to, you could use them as containers for information along the way. With response being probably the more apt place to store them. Just be mindful that if overwrite something, you can break everything. (i.e., res.write = null results in a dead application).

The best way to avoid getting lost is: a) try to come up with a test b) see if someone else is doing it - how? c) look at the source. Unfortunately Express has quite a source. So that's why a) is a good starting point.

  • Thanks much for the reply. I'm seeing that the best practice seems to be using the response object for all data throughout the middleware pipline. It just doesn't really feel conceptually correct to me but that's what the docs and multiple other posters have said. I guess I'm going to conceptualize it like the request 'ends' at the application entry point. And then on you're just using its data and building the response object. It makes sense and I can deal with that. – Dr. Chocolate Oct 11 '16 at 23:58