使用express
我有“公共”路由和“API”路由,应该由express-jwt
进行身份验证。
// define public routes in a router
const routerPublic = express.Router();
routerPublic.route("/login", (req, res) => /* whatever */);
routerPublic.route("/about-us", (req, res) => /* whatever */);
routerPublic.route("/foo/bar/baz", (req, res) => /* whatever */);
// define API routes in a router
const routerApi = express.Router();
routerApi.route("/api/v1/foo", (req, res) => /* whatever */);
routerApi.route("/api/v1/bar", (req, res) => /* whatever */);
// add routers to express app
app.use(routerPublic); // (1)
app.use(routerApi, jwt({ secret: "secret" })); // (2)
所以我填充了两个express.Router
实例 - 一个具有不安全的路由,另一个具有安全路由。然后我将这些路由器加载到快速应用程序中,只有安全的路由才能进行身份验证。
但顺序很重要。如果第(1)行在(2)之前出现,则它按预期工作。但如果(2)出现在(1)之前,那么一切都经过认证,包括安全和不安全的路线。
所以有竞争条件,我不明白。
回答如下:发布它作为答案,以帮助他人,
您使用新的快速路线,可以尝试这样的事情:
routerApi.use(jwt({ secret: "secret" }))