Node Cors捕获中间件回调错误 [英] Node cors catch middleware callback error
问题描述
我有以下代码使用express和npm cors插件来检查原始标头并允许访问
I have the following code to check the origin header and allow access, using express and the npm cors plugin
const app = express();
const cors = require('cors')
var corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
现在,我想知道是否有办法捕获新错误回调?
Now I wonder if there is way to catch the "new Error" callback?
并发回400个http状态?
And send back a 400 http status?
谢谢!
推荐答案
是的,这在Express文档中的错误处理。
Yes, this is explained in the Express docs under Error Handling.
Express带有内置的错误处理程序,可以处理在应用程式。该默认的错误处理中间件功能已添加到中间件功能栈的末尾。
Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
如果将错误传递给 next()
,并且您不会在自定义错误处理程序中进行处理,它将由内置错误处理程序进行处理;错误将与堆栈跟踪一起写入客户端。堆栈跟踪不包含在生产环境中。
If you pass an error to next()
and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.
文档不会对那进行过多介绍有关默认处理程序的更多详细信息,但在查看源代码之后,默认处理程序是名为 finalhandler
。
The docs don't go into that much more detail on the default handler, but after looking at the source code, the default handler is a separate module called finalhandler
.
无论如何,要覆盖此处理程序,请参阅Express文档中标题为 编写错误处理程序 。
Anyways, to override this handler, refer to the section in the Express docs titled Writing error handlers.
它解释:
以与其他中间件功能相同的方式定义错误处理中间件功能,除了错误处理功能有四个参数,而不是三个:
(错误,要求,结果,下一个)
。例如:
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
在其他 app.use()
和路由调用之后,最后定义错误处理中间件
You define error-handling middleware last, after other app.use()
and routes calls
因此,在您的情况下,如果您想回答400,则可能会这样写:
So in your case, if you wanted to respond with a 400, you might write something like this:
const app = express();
const cors = require('cors')
var corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
// This overrides the default error handler, and must be called _last_ on the app
app.use(function customErrorHandler(err, req, res, next) {
res.status(400).send('Your custom error message here');
});
也可以在其存储库中包含示例服务器,显示了此erorr处理覆盖。
Express also includes a sample server in its repo, showing this erorr handling override.
这篇关于Node Cors捕获中间件回调错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!