这是我的代码,它是用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 ”,网页显示“这是一个详细信息页面”。为什么在这两种情况下结果不同?
2 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
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();
});
添加回答
举报
0/150
提交
取消