我在express.Router()中添加中间件时遇到问题。
let router = express.Router();
let mid = function(req, res, next) {
console.log("mid");
next();
}
router.get("/", function(req, res) {
res.send("public");
})
let userRouter = express.Router();
userRouter.use(mid);
userRouter.get("/users", function(req,res) {
res.send("users");
})
router.use(userRouter);
app.use("/", router);
router = express.Router();
router.get("/", function(req, res) {
res.send("api");
})
app.use("/api", router);
以下是结果:
访问" /"不要触发中间件。 访问" / users"触发中间件。 访问" / api"触发中间件。
我不明白为什么" / api"正在触发中间件。
答案 0 :(得分:0)
检查Express documentation for router middleware。
Express API documentation也可能有用。
我组织了一些代码,现在它可以正常工作了。
'use strict';
let express = require('express');
let expressApp = express();
// --- middleware function ---
let usersMiddleware = function(req, res, next) {
console.log("users router middleware");
next();
}
// --- middleware function ---
let appMiddleware = function(req, res, next) {
console.log("app middleware");
next();
}
// --- public router ---
let publicRouter = express.Router();
publicRouter.get("/", function(req, res) {
res.send("public");
});
// --- user router ---
let userRouter = express.Router();
// --- this is a router based middleware,
// --- to be used only for this router ---
userRouter.use(usersMiddleware);
userRouter.get("/", function(req,res) {
res.send("users");
});
// --- api router ---
let apiRouter = express.Router();
apiRouter.get("/", function(req, res) {
res.send("api");
});
// --- this is a app based middleware,
// --- it will be used for every route of the app after this line
expressApp.use(appMiddleware);
// --- adding the routers to the app ---
expressApp.use("/", publicRouter);
expressApp.use("/users", userRouter);
expressApp.use("/api", apiRouter);
expressApp.listen(8080);
请注意,此处使用了两种中间件,一种连接到特定路由器(即您想要的路由器),另一种连接到应用,用于所有其他路由(我添加了此一个显示差异)。
/api
触发了中间件,因为您将其添加到app
而不是路由器实例。