我希望在/api
路径下有不同的路由和不同的中间件处理程序.具体地说,不同的API路由应该允许不同的身份验证方式.
我以为我可以用不同的中间件在两个不同的Router
下嵌套不同的API路由:
const express = require("express");
const app = express();
const port = 4000;
const one = express.Router();
one.use((req, res, next) => {
console.log("one");
next();
});
one.get("/api/one", (req, res) => {
console.log("/api/one");
res.send("one");
});
// ---
const two = express.Router();
two.use((req, res, next) => {
console.log("two");
next();
});
two.get("/api/two", (req, res) => {
console.log("/api/two");
res.send("two");
});
// ---
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.use(one);
app.use(two);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
我预计导航到/api/one
时会记录one
,导航到/api/two
时会记录two
,但是导航到/api/two
时会运行both个中间件:
Example app listening on port 4000
one
/api/one
one
two
/api/two
有没有办法实现我想要的without for each 单独的API路由列出不同的中间件?