简体   繁体   English

Node Cors捕获中间件回调错误

[英]Node cors catch middleware callback error

I have the following code to check the origin header and allow access, using express and the npm cors plugin 我有以下代码,使用express和npm cors插件检查原始标头并允许访问

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? 现在,我想知道是否有办法捕获“新错误”回调?

And send back a 400 http status? 并发回400 http状态?

Thanks! 谢谢!

Yes, this is explained in the Express docs under Error Handling . 是的,这在Express文档中的Error Handling下进行了说明。

Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. Express带有内置的错误处理程序,可处理应用程序中可能遇到的任何错误。 This default error-handling middleware function is added at the end of the middleware function stack. 默认的错误处理中间件功能已添加到中间件功能堆栈的末尾。

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; 如果将错误传递给next()并且未在自定义错误处理程序中进行处理,则它将由内置错误处理程序进行处理; the error will be written to the client with the stack trace. 错误将与堆栈跟踪一起写入客户端。 The stack trace is not included in the production environment. 堆栈跟踪不包含在生产环境中。

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 . 该文档不进入的默认处理程序更多的细节,但在看源代码 ,默认的处理程序是被称为一个独立的模块finalhandler

Anyways, to override this handler, refer to the section in the Express docs titled Writing error handlers . 无论如何,要覆盖此处理程序,请参阅Express文档中标题为“ 编写错误处理程序”的部分

It explains: 它说明:

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next) . 定义错误处理中间件功能的方式与其他中间件功能相同,只是错误处理功能具有四个参数而不是三个参数: (err, req, res, next) For example: 例如:

 app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') }) 

You define error-handling middleware last, after other app.use() and routes calls 在其他app.use()之后,您最后定义错误处理中间件并路由调用

So in your case, if you wanted to respond with a 400, you might write something like this: 因此,在您的情况下,如果您想回复400,则可以这样写:

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');
});

Express also includes a sample server in its repo, showing this erorr handling override. Express在其存储库中还包含一个示例服务器 ,显示了此erorr处理覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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