gpt4 book ai didi

node.js - Express-Mongoose Exp的请求-响应周期/错误处理

转载 作者:行者123 更新时间:2023-12-03 08:21:41 25 4
gpt4 key购买 nike

我的印象是res.send()结束了请求-响应周期,但是在else块中没有return的情况下,调用next(ex),它将响应对象传递给错误处理中间件,从而导致Error: Can't set headers after they are sent.
我的理解力在哪里?如果很重要,我正在使用express-async-errors捕获错误。

router.get('/', async (req, res, next) => {
// get all staff sorted by name
const allStaff = await Staff.find().sort('name');
if (!allStaff) {
res.status(404).send('No staff');
} else {
return res.status(200).send(allStaff);
}
next(ex);
});

最佳答案

在您的问题中,您自己提到next()函数将响应对象传递给错误处理中间件,因此即使您不希望下一个中间件执行,即将成功发送allstaff,但接下来会执行next()函数将被调用。

您正在做什么(在else块中不返回):

发送allstaff对象并因此尝试结束请求响应周期,但随后调用next()从而调用下一个中间件,该中间件试图弄乱原本应该成功的请求响应周期。

router.get('/', async (req, res, next) => {
// get all staff sorted by name
const allStaff = await Staff.find().sort('name');
if (!allStaff) {
res.status(404).send('No staff');
} else {
res.status(200).send(allStaff); //send the response..expect the req-res cycle to end
}
next(ex); //then call next which might try to hamper the outgoing response
});

您应该怎么做:

如果您发送响应,那么它绝不会遇到试图再次发送响应的其他语句,我个人更喜欢以下代码:
router.get('/', (req, res, next) => {
// get all staff sorted by name
Staff.find().sort('name').exec(function (err, docs) { //this callback function will handle results
if (err) {
next(); //if there is an error..then the next middleware will end the req response cycle
} else {
if (docs.length == 0) {
res.status(404).send('No staff'); //send response,the req- res cycle ends,never disturbed again...story finished
} else {
res.status(200).send(docs); //send response,the req- res cycle ends,never disturbed again.....story finished
}
}
});


});

关于node.js - Express-Mongoose Exp的请求-响应周期/错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com