【问题标题】:express cors blocked only on root route of some apiexpress cors 仅在某些 api 的根路由上被阻止
【发布时间】:2020-04-15 15:23:16
【问题描述】:

由于提供自定义 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.js express cors


    【解决方案1】:

    我不太确定我是否理解这个问题,但我还是会抓住机会回答..

    路由器是 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'));
    

    【讨论】:

    • 不,我的意思是当你这样做的时候。根/ 仍将被cors 阻止。我在 index.ts (main) 上确实有适当的 cors 设置
    • @uzu 尝试做 app.use((res, req, next) => { ... /* Cors 设置 */ } );
    猜你喜欢
    • 2023-04-03
    • 2019-07-06
    • 2020-12-25
    • 2020-10-24
    • 2020-08-16
    • 2021-04-24
    • 2023-04-01
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多