推荐答案
在 Express 中,next 函数是一个回调函数,用于将控制权传递给下一个中间件或路由处理程序。通过调用 next(),Express 会继续执行后续的中间件或路由处理程序。如果 next 函数被传递了一个参数(例如 next(err)),Express 会跳过所有剩余的中间件,直接进入错误处理中间件。
本题详细解读
1. next 函数的基本用法
在 Express 中,中间件函数通常有三个参数:req(请求对象)、res(响应对象)和 next(回调函数)。next 函数的作用是将控制权传递给下一个中间件或路由处理程序。例如:
// www.javascriptcn.com code example
app.use((req, res, next) => {
console.log('Middleware 1');
next(); // 将控制权传递给下一个中间件
});
app.use((req, res, next) => {
console.log('Middleware 2');
next(); // 将控制权传递给下一个中间件
});
app.get('/', (req, res) => {
res.send('Hello World');
});在这个例子中,next() 的调用使得 Express 能够依次执行 Middleware 1 和 Middleware 2,最后执行路由处理程序。
2. next 函数的错误处理
如果 next 函数被传递了一个参数(例如 next(err)),Express 会跳过所有剩余的中间件,直接进入错误处理中间件。例如:
// www.javascriptcn.com code example
app.use((req, res, next) => {
const err = new Error('Something went wrong');
next(err); // 传递错误对象,跳过后续中间件
});
app.use((req, res, next) => {
console.log('This middleware will not be executed');
next();
});
app.use((err, req, res, next) => {
res.status(500).send(err.message); // 错误处理中间件
});在这个例子中,由于 next(err) 被调用,Express 会跳过第二个中间件,直接进入错误处理中间件。
3. next('route') 的特殊用法
next('route') 是一种特殊的用法,它用于跳过当前路由的所有剩余中间件,直接进入下一个匹配的路由。例如:
// www.javascriptcn.com code example
app.get('/user/:id', (req, res, next) => {
if (req.params.id === '0') {
next('route'); // 跳过当前路由的剩余中间件,进入下一个匹配的路由
} else {
next(); // 继续执行当前路由的剩余中间件
}
}, (req, res, next) => {
res.send('Regular User');
});
app.get('/user/:id', (req, res) => {
res.send('Admin User');
});在这个例子中,如果 id 为 0,next('route') 会跳过当前路由的剩余中间件,直接进入下一个匹配的路由,即返回 Admin User。