aluckdog
2021-10-29 13:42:05
這是我的代碼,它是用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
提交
取消