gpt4 book ai didi

javascript - 路线 ('next' )在 ExpressJS 中做什么?

转载 作者:行者123 更新时间:2023-11-30 12:22:27 25 4
gpt4 key购买 nike

documentation它说:

You can provide multiple callback functions that behave just like middleware, except these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.

这是否意味着如果我这样写一个路由:

app.get('/', function(req, res, next) {
if (!req.params.id) {
res.statusCode(400).send({error: "id parameter is required"});
next('route');
} else {
next();
}
}, function(req, res) {
res.send({something: 'something'})
});

params.idundefined,那么下一条路由就不会被执行,但如果它存在,它会执行吗?

编码/命名约定基本上让我有点困惑。为什么不是 next(false) 而不是 next('route')

最佳答案

我找到了答案。使用 app 或 Express 路由器时,您可以为同一路径定义多个路由:

// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// logic
}, function (req, res, next) {
// logic
});

// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// logic
});

如果您从第一个路由的任何回调(中间件)调用 next('route')组路由 将被跳过并将控制传递给下一组路由:

// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
next('route')
}, function (req, res, next) {
// this middleware won't be executed at all
});

// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// the next('route') in the first callback of the first set of routes transfer control to here
});

现在使用 next('route') 而不是 next(false) 更有意义:它将控制转移到为当前路径定义的下一个路由。

关于javascript - 路线 ('next' )在 ExpressJS 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30541342/

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