在表达中如何工作 next()



我想我知道为什么我们在 expressjs 中使用 next() 理论上: :)

实际上,路由方法可以将多个回调函数作为参数。对于多个回调函数,重要的是提供 next 作为回调函数的参数,然后在函数主体中调用 next() 以将控制权移交给下一个回调。

但实际上我无法得到它。

app.get('/project', (req, res, next) => {
con.query("SELECT * FROM issues", (err, result) => {
if (err) throw err;
res.send(result);
})
next()
console.log("NEVER HERE");
});

这是此代码不起作用的情况。

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

  1. 但是,如果我next()右边的下面res.send(result);并删除console.log('NEVER HERE');声明上方的这个,它就可以完美地工作。

  2. 此外,如果我在两个地方都删除next(),它运行良好。

  3. 我注意到的是,如果我使用console.log(result)而不是res.send(result)next()回调在哪里不起作用。

我的主要问题是,当一个人与res.send()一起使用时,为什么一个next()给另一个人"制造麻烦".

我是新手表达,也是mysql,提前谢谢你。 :)

不应该同时使用res.sendnext

next的目的是将控制权传递给另一个中间件,但是当您使用res.send(...)响应请求时,就没有理由这样做了。

使用next时的简单示例:

app.get('/admin', function authMiddleware(req, res, next){
// user must be logged in and be an admin to access this route
if (req.user && req.user.isAdmin)
next(); // this will pass control to the handler function bellow
else // respond with 401 error
res.status(401).send('unauthorized');
}, function handler(req, res){
// only get here when user is admin
res.render('admin');
});

您的示例应如下所示,您根本不需要关心next

app.get('/project', (req, res) => {
con.query("SELECT * FROM issues", (err, result) => {
// don't throw, just respond appropriately
//if (err) throw err;

if (err)
res.status(500).send('error occured');
else
res.send(result);
});
// calling `next` here doesn't make any sense unless you pass an error
});

您可以使用next函数,但您应该设置一个错误处理程序,并且您需要传递错误 (Docs):

app.get('/project', (req, res, next) => {
con.query("SELECT * FROM issues", (err, result) => {
// don't throw, just respond appropriately
//if (err) throw err;

if (err)
next('error occured');
else
res.send(result);
});
});
// Error handler
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).send('error occured')
});

最新更新