gpt4 book ai didi

node.js - 如何绕过express中的中间件

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:29 24 4
gpt4 key购买 nike

我正在尝试使用 next('route') 绕过其中一个中间件。即使这样,控制权也会传递给下一个中间件,而不是传递给路由路径。

fun1 = (req,res,next) =>{
res.locals.isLogin = true;
next('route');
}

fun2 = (req,res,next) =>{
res.locals.isLogin1 = true;
next();
}

app.use(fun1);
app.use(fun2);

app.get('/',(req,res,next)=>{
res.write('<h1>Hello ' + res.locals.isLogin + ' and ' + res.locals.isLogin1);
res.end();
});

Response

最佳答案

next('route') 工具不会跳过通过 use() 函数添加的中间件,请参阅:Using middleware

Documentation : To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

因此,要跳过 fun2,这里是对代码的更改,

fun1 = (req,res,next) =>{
res.locals.isLogin = true;
next('route');
}

fun2 = (req,res,next) =>{
res.locals.isLogin1 = true;
next();
}

app.get('/', fun1, fun2);

app.get('/',(req,res,next)=>{
res.write('<h1>Hello ' + res.locals.isLogin + ' and ' + res.locals.isLogin1);
res.end();
});

关于node.js - 如何绕过express中的中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413288/

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