【问题标题】:Is it the right way to end request-response cycle in nodejs/express middleware?在 nodejs/express 中间件中结束请求-响应周期是否正确?
【发布时间】:2019-11-12 06:50:55
【问题描述】:

我的 nodejs/express 项目中有一个中间件函数auth_deviceid 来检查提交的device_id。如果 device_id 不满足特定条件,则应终止请求-响应周期。我想知道我的代码是否正确结束请求-响应周期。这里是auth_deviceid

module.exports = function(req, res, next) {
    const user_device_id = (req.query._device_id || req.body._device_id);
    if (!user_device_id || user_device_id.length < 10) return res.status(400).send('Missing device id!');

    next();
}

上述中间件函数在路由中被调用:

router.post('/verif', [auth_deviceid], async (req, res) => {....}

我的问题是,如果user_device_id为空,上面的router.post会被拒绝(auth_deviceid返回false)吗?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    是的,看起来不错 - 如果不满足条件,您将通过内部调用 res.end()res.send() 返回。

    【讨论】:

      【解决方案2】:

      不是在中间件中调用res.send,而是让next 处理错误,然后仅由一个错误处理程序处理所有错误。

      中间件

      module.exports = function(req, res, next) {
          const user_device_id = (req.query._device_id || req.body._device_id);
          if (!user_device_id || user_device_id.length < 10) return next(new Error('MISSING_DEVICE_ID'));
          // I like a custom error like `new MissingDeviceError()`
      
          next();
      }
      

      然后,在您的 express 应用程序的错误处理程序中,只需检查错误类型:

      app.use(function (err, req, res, next) {
        console.error(err.stack)
        if (err.message === 'MISSING_DEVICE_ID') {
          return res.status(400).send('Missing device id!');
        }
        // another error
        res.status(500).send('Something broke!')
      })
      

      【讨论】:

        猜你喜欢
        • 2013-03-12
        • 2011-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多