【问题标题】:How access Response in Express outside Route controller如何在路由控制器外部访问 Express 响应
【发布时间】:2022-01-24 12:14:12
【问题描述】:

我正在使用 Express JS 作为后端 API。

我只需要使用自定义服务中的 res 对象,而不是路由控制器。

当然我是从控制器调用服务函数,我知道我可以轻松地将 res 作为参数传递并访问它,但我想知道是否有其他情况或更好的做法。

const videoaskResponse = async (req, res, next) => {
  try {
    await webhookService.handleVideoaskResponse(req.body, res)

    res.status(200).json({ received: true })
  } catch (error) {
    next(error)
  }
}

这是我如何处理这种情况的示例。

【问题讨论】:

    标签: javascript node.js api rest express


    【解决方案1】:

    您走在正确的轨道上,最佳做法是将 res 作为函数参数传递。

    另一种可能的非行业标准方法是从 webhookService.handleVideoaskResponse 返回一个对象。

    然后您可以将 res 对象的字段设置为从您的函数调用返回的该对象的字段。这会将编辑 res 对象的逻辑放在路由器而不是服务中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多