这是我的代码,它是用Node express构建的。在接下来的(“路径”)不2种类似的情况一致的工作。
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") 会将控制权传递给下一个路由。
所以我认为它应该显示"this is a details page"而不是"this is a scenario when id is 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");
});
我简单地取代了router.use与router.get,而这一次,当我重温“ HTTP://本地主机:8080 /消息/ 2 ”,网页显示“这是一个详细信息页面”。
为什么在这两种情况下结果不同?
慕娘9325324
陪伴而非守候
相关分类