简体   繁体   中英

How access Response in Express outside Route controller

I am using Express JS for backend API.

I need to simply use res object from custom service, not route controller.

Of course I am calling service function from controller and I know that I can easily pass res as an argument and access it, but I wonder if there is other case or maybe better practice.

 const videoaskResponse = async (req, res, next) => { try { await webhookService.handleVideoaskResponse(req.body, res) res.status(200).json({ received: true }) } catch (error) { next(error) } }

Here's example how I handle that case.

you are on the right track the best practice is to pass res as a function argument.

Another possible approach which is not industry standard is to return an object from webhookService.handleVideoaskResponse.

Then you can set the fields of the res object to the fields from that object returned from your function call. This would put the logic of editing the res object in the router rather than the service.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM