简体   繁体   English

表达错误中间件发送响应

[英]Express error middleware sending response

In my express application when the error middleware is reached it still executes the second middleware function after res.json . 在我的express应用程序中,当到达错误中间件时,它仍执行res.json之后的第二个中间件功能。 The docs says that: 文档说:

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. 下表中响应对象(res)上的方法可以向客户端发送响应,并终止请求-响应周期。 If none of these methods are called from a route handler, the client request will be left hanging. 如果从路由处理程序中未调用这些方法,则客户端请求将被挂起。

Where res.json is one of the methods in the table which would terminate the request-response cycle. 其中res.json是表中将终止请求-响应周期的方法之一。 Also I don't call next in my express error middleware 我也不会在我的明示错误中间件中调用next

router.use((err, req, res, next) => {
    res.json({
        success: false,
        message: 'fail: email already exists'
    });
});


//test still gets logged even though the express error middleware is executed
router.post('/', (req, res , next) => {
    console.log('test');

});

Question: 题:

Why is the second express middleware still executed even though I don't call next in the error middleware and execute res.json() ? 即使我不在错误中间件中不调用next并执行res.json()为什么第二个express中间件仍仍执行?

Per the documentation on error handling you must specify the error handling middleware last for it to work properly. 根据有关错误处理文档,您必须最后指定错误处理中间件才能使其正常工作。

It is likely that by having that with an error signature that is is getting confused. 通过带有错误签名的错误可能会引起混淆。

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

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