【问题标题】:Express js middleware not working when error is passed alongside ,req,res and next当错误与,req,res和next一起传递时,Express js中间件不起作用
【发布时间】:2020-11-11 21:52:30
【问题描述】:

所以,我正在尝试在 express 中实现 CSRUF,我希望抛出自定义错误,而不是中间件 CSRUF example here 的默认错误处理。 CSRF 实施工作正常,当令牌无效时,控制台会抛出错误,并向浏览器发送状态为 403 的响应。 我不希望默认处理错误。 当我创建如下自定义错误处理程序中间件时,

 function (err,req, res, next) {
    console.log("reached")
    if (err.code !== 'EBADCSRFTOKEN') return next(err)

    console.log("Not working")
    // handle CSRF token errors here
    res.status(500)
    res.send('form tampered with')
}

似乎没有实现中间件,因为正在抛出 CSRUF 的默认错误。

有趣的是,我注意到当我有一个带有 err 参数的自定义中间件时,该中间件似乎被应用程序忽略了。 示例(这有效)

 function (req, res, next) {
     console.log("This is some middleware") //Console outputs
      next()
   
}

但是,当我在下面的函数中添加 err 或 error 参数时,看起来好像没有使用中间件

function (req, res, next) {
         console.log("This is some middleware.Err parameter has been passed") //Nothing is output to console
         next()
    }

我已阅读Express error handling documentation 并按要求完成,但我仍然面临错误,可能是什么问题以及如何处理。

【问题讨论】:

  • 在调用.use() 处理其他所有错误处理程序之后,是否为每个错误处理程序调用.use(errorhandler)?错误处理程序必须是 used 最后。
  • 具体在哪里?能不能给个图让我理解一下

标签: node.js express csrf middleware


【解决方案1】:

我终于明白了。 当我将错误处理程序中间件放在 CSRUF 之后,一切正常,即

app.post(route,middleware1,errorhandler,(req,res)={
//Any errors from middleware1 will now be catched by the errorhandler instead of the default error handler
//Some code here
})

错误处理程序的位置似乎起了很大的作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多