首页 > 解决方案 > express cors 仅在某些 api 的根路由上被阻止

问题描述

由于提供自定义 OPTIONS 方法,我有自定义 cors 设置。下面的代码



// region cors
// app.use(cors()); // - fixme > using cors lib will disable http options for all routes. avoid using it.
app.all('/*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Authorization");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD, OPTIONS")
    next();
});
// endregion cors

这是一些路线。行为怪异。

const router = express.Router();

router.options(`/`,  authMiddleware, options);
router.get(`/term`, authMiddleware, search);
router.get(`/`, authMiddleware, search);
router.get(`/recent`, authMiddleware, getRecentSearchHistory);

export {router}


你可以看到 ~/term/是相同的。我~/term另外制作了它以检查它是否正常工作。

问题是,api请求/会被阻止!!?出于某种原因,/term工作得很好,但 express 只会阻止/根路由。(实际的绝对路线是http://localhost:3000/api/search

express有没有专门为“搜索”或什么的路线名称保留?

我不明白这种行为。

标签: node.jsexpresscors

解决方案


我不太确定我是否理解这个问题,但无论如何我都会有机会回答..

路由器是 express 的一个新实例,它不继承应用程序的 cors 设置,我有一段时间没有使用 express 路由器,但我认为如果你让路由器也使用 cors,它可能会工作,如果你想要/路由到不要被/*我建议的路线抓住,也许可以在应用程序路线上方定义它。

这是我的意思的一个例子

import express from 'express'
import cors from 'cors';

const router = express.Router();
router.use(cors());

router.options(`/`,  authMiddleware, options);
router.get(`/term`, authMiddleware, search);
router.get(`/`, authMiddleware, search);
router.get(`/recent`, authMiddleware, getRecentSearchHistory);

const app = express();
app.use(cors());

app.use(router);

// app.use('/index/', index);

app.listen(3000, () => console.log('app listening'));

推荐阅读