Access current req object everywhere in Node.js Express

前端 未结 2 1165
别跟我提以往
别跟我提以往 2021-02-07 15:57

I wonder how to access req object if there\'s no \'req\' parameter in callback.

This is the scenario:
In ExpressJs, I have a common function, it uses to handle somet

相关标签:
2条回答
  • 2021-02-07 16:51

    Actually, this is possible with something like global-request-context

    This is using zone.js which let you persist variables across async tasks.

    0 讨论(0)
  • 2021-02-07 16:58

    The only proper way is to pass the req object through as an argument to all functions that need it.

    Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.

    You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.

    There is no shortcut here. You will just have to pass the req object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.

    There are some circumstances where you may be able to use a closure to "capture" the desired req object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.

    0 讨论(0)
提交回复
热议问题