node.js - 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有没有专门为“搜索”或什么的路线名称保留?
我不明白这种行为。
解决方案
我不太确定我是否理解这个问题,但无论如何我都会有机会回答..
路由器是 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'));
推荐阅读
- html - Mat-card 有 80% 的时间重叠
- python - python 电子邮件会生成无效的消息 ID 还是 gmail 替换有效的消息 ID?
- python - 当我尝试安装任何库时出现运行时错误(需要 python 3.5 或更高版本)
- java - Google登录失败Firease身份验证android
- c# - 如何在 iOS 上使用 CardView 获得清晰的提升效果?
- vba - 来自特定标头的 VBA 拾取值并在行中使用它
- android - MotionLayout 左右滑动动画问题
- r - 对 R 中的 n 个数据帧重复相同的过程
- python - Tensorflow:Mac OS 摄像头已打开,但视频在屏幕上不可见
- python - 当我第一次在本地主机 127.0.0.1:8000 上运行我的 django 项目时,它可以正常打开,但现在添加产品后它显示 127.0.0.1 拒绝连接