为什么即使在 express 中调用 next() 之后,底层代码也会在一个块中执行?
why the underlying code gets executed in a block even after invoking next() in express?
exports.getTour = catchAsync(async (req, res, next) => {
const tour = await Tour.findById(req.params.id);
if (!tour) {
next(new AppError('No tour found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
tour
}
});
});
如果游览变量为空,我将调用 next() 方法并使用 class 构造函数在其中创建错误,但即使在调用 next() 之后,响应也会作为对请求的响应发送,然后出现“[ERR_HTTP_HEADERS_SENT]:”错误。为什么即使在调用 next 之后块也没有退出?
因为如果 tour
为空,您需要 return
才能中断函数。
所以这样做
if (!tour) {
return next(new AppError('No tour found with that ID', 404));
}
next()
使当前回调函数传递给具有相同 URL 的下一个请求。如果回调函数中没有激活响应,则请求无法完成。要完成回调函数,应使用任何函数编写响应。要在回调中使用 next()
应该有另一个请求,如
// request to be passed by `next()`
app.request('same URL', (res, req) => {
...
res.end()
});
这是an example on express document about next()
。
如果您想以发送错误结束,则只需响应 JSON res.status(404).send("error": "No tour found with that ID")
。
在一个中间件中,你应该执行next()函数,try
module.exports.getTour = async (req, res, next) => {
const tour = await Tour.findById(req.params.id);
if (!tour) res.send("No tour found with that ID");
req.tour = tour;
next();
};
exports.getTour = catchAsync(async (req, res, next) => {
const tour = await Tour.findById(req.params.id);
if (!tour) {
next(new AppError('No tour found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
tour
}
});
});
如果游览变量为空,我将调用 next() 方法并使用 class 构造函数在其中创建错误,但即使在调用 next() 之后,响应也会作为对请求的响应发送,然后出现“[ERR_HTTP_HEADERS_SENT]:”错误。为什么即使在调用 next 之后块也没有退出?
因为如果 tour
为空,您需要 return
才能中断函数。
所以这样做
if (!tour) {
return next(new AppError('No tour found with that ID', 404));
}
next()
使当前回调函数传递给具有相同 URL 的下一个请求。如果回调函数中没有激活响应,则请求无法完成。要完成回调函数,应使用任何函数编写响应。要在回调中使用 next()
应该有另一个请求,如
// request to be passed by `next()`
app.request('same URL', (res, req) => {
...
res.end()
});
这是an example on express document about next()
。
如果您想以发送错误结束,则只需响应 JSON res.status(404).send("error": "No tour found with that ID")
。
在一个中间件中,你应该执行next()函数,try
module.exports.getTour = async (req, res, next) => {
const tour = await Tour.findById(req.params.id);
if (!tour) res.send("No tour found with that ID");
req.tour = tour;
next();
};