最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

带有 express 后端的 React 应用程序存在 CORS 问题。 (我正在使用 docker)

网站源码admin38浏览0评论

带有 express 后端的 React 应用程序存在 CORS 问题。 (我正在使用 docker)

带有 express 后端的 React 应用程序存在 CORS 问题。 (我正在使用 docker)

我一直面临着 docker 和 CORS 的一个非常尴尬的问题。 相同的代码在本地机器上完美运行。 我正在使用 npm 包 cors。 我的后端在 pert 3000 上运行,前端在 4000 上运行。 这是我的 app.ts 文件中的代码。

this.app.use((req, res, next) => {
      
        // TODO Add origin validation
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma');
      
        // intercept OPTIONS method
        if (req.method === 'OPTIONS') {
          res.sendStatus(204);
        } else {
          next();
        }
      });
    this.app.options('*', cors());

这是我的配置文件的代码

allowedDomains: ["http://localhost:3000","http://localhost:4000"]

我还在 package.json 文件中添加了代理

    "proxy": "http://localhost:3000/api"

这里是浏览器控制台的错误

编辑

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/lighting/lighting. (Reason: CORS request did not succeed). Status code: (null).

编辑2

Access-Control-Allow-Origin *

当我仅向 api 发出请求时,即在 3000 端口上,这是在响应标头中出现的,但是当我向前端发出请求时,这不会出现。

但仍然没有运气。 我已经在这个问题上停留了 2 天多了。 非常感谢任何帮助。 谢谢

回答如下:
发布评论

评论列表(0)

  1. 暂无评论