这是我的代码,它是用 Node express 构建的。 next(“ route”)在两种相似的情况下无法统一工作。
let express = require("express");
let app = express();
let router = express.Router();
router.use("/message/:id", function (req, res, next) {
console.log(typeof req.params.id);
if (req.params.id === 1 + "") {
console.log("the current id is 1");
next();
} else if (req.params.id === 2 + "") {
console.log("the current id is 2");
next("route");
} else if (req.params.id === 3 + "") {
console.log("the current id is 3");
next("router");
} else {
res.send("no id matched");
}
}, function (req, res) {
res.send("this is a scenario when id is 1");
});
router.use("/message/:id", function (req, res) {
res.send("this is a details page");
});
app.use("/", router, function (req, res) {
res.send("this is triggered by the app");
});
app.listen(8080, function () {
console.log("Please visit localhost:8080");
});
当我这样输入URL地址:“ http://localhost:8080/message/2” 时,Node REPL控制台输出:“当前ID为2” ,并且网页显示:“这是id为1的情况” 。
我对此很困惑。根据express的官方文档,next(“ route”)会将控制权传递给下一条路线。
因此,我假设它应该显示“这是一个详细信息页面” ,而不是“这是id为1的情况” 。为什么?
为了找出更多信息,我还对代码做了一些更改:
let express = require("express");
let app = express();
let router = express.Router();
router.get("/message/:id", function (req, res, next) {
console.log(typeof req.params.id);
if (req.params.id === 1 + "") {
console.log("the current id is 1");
next();
} else if (req.params.id === 2 + "") {
console.log("the current id is 2");
next("route");
} else if (req.params.id === 3 + "") {
console.log("the current id is 3");
next("router");
} else {
res.send("no id matched");
}
}, function (req, res) {
res.send("this is a scenario when id is 1");
});
router.get("/message/:id", function (req, res) {
res.send("this is a details page");
});
app.use("/", router, function (req, res) {
res.send("this is triggered by the app");
});
app.listen(8080, function () {
console.log("Please visit localhost:8080");
});
我只是将 router.use 替换为 router.get ,这次是当我重新访问“ http://localhost:8080/message/2” 时,该网页显示“这是详细信息页面” 。
为什么在两种情况下结果都不一样?
答案 0 :(得分:0)
在docs中指出
要从路由器中间件堆栈中跳过其余中间件功能,请调用next('route')将控制权传递给下一条路由。注意:next('route')仅在使用app.METHOD()或router.METHOD()函数加载的中间件函数中起作用。
请注意“注意”部分,next('route')是要跳过的,但在第一种情况下,因为您没有使用route.METHOD(),而是使用router.use()
答案 1 :(得分:0)
router.get仅用于定义子路径
var router = express.Router();
app.use('/api', router); // Mount the router as middleware at path /api
router.get('/signup', signup);
router.get('/user', userInfo);
If you open /api/signup, then the signup function will get called.
If you open /api/user, then the userInfo function will get called.
在使用router.use()时,您只能提供中间件,如下所示:
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});