简体   繁体   中英

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 . 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. 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. Also I don't call next in my express error middleware

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() ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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