how to access request or response objects in express.Js anywhere?

in an express.Js app ;i want to write a controller class that handles the request & response for other controllers for example add data to locals in res object or delete data from req.session etc.

is there a way i can do it without passing req or res as an argument
can i access them globally

>Solution :

The correct and possible way is to pass the req object as an argument to functions that need to use it.

Placing it in global variables will not work because multiple requests can be processed at the same time if for example requests use some asynchronous calls as part of their processing. So, multiple requests will stomp on other requests and will make it really hard to track down bug.

node.js is a server that can potentially handle many requests for many clients. Server may have many requests all in flight at the same time and thus plain globals you wish to use cannot be used for request-specific data.

Leave a Reply