CORS 策略适用于某些网络

问题描述 投票:0回答:1

我在我的域上的 Node JS (https://exemple.com/postRequest) 中创建了一个 API,以及一个 React 应用程序 (https://exemple.vercel.app 例如)。在我的私人网络(主页)上,一切正常,我的 React 应用程序通过 Post REQUEST 获取 API url,并且它正在工作。但是,在工作中,它不再起作用了,我收到以下消息:

Access to fetch at 'https://myapi.com/postRequest' from origin 'http://exemple.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

为了测试,我在我的express应用程序上使用nodeJs Cors来允许所有。当我在家时它就可以工作

app.use(cors())

两者都在服务器上,我不知道为什么我的连接会影响帖子请求?您有信息和/或解决方法吗?

感谢您的帮助

reactjs node.js cors
1个回答
0
投票

在家能工作但在工作时不能工作的原因很可能是由于网络配置或网络安全性的变化。

要解决此问题,请设置 Node.js Express 服务器以包含必要的 CORS 标头,以接受来自 React 应用程序域的请求。您可以在 CORS 中间件中指定允许的来源,而不是允许所有来源。

这就是我认为会起作用的


const cors = require('cors');

const corsOptions = {
  origin: 'https://exemple.vercel.app',
  // origin: ['https://exemple.vercel.app', 'https://another-domain.com'],
};

app.use(cors(corsOptions));

您可以在数组内添加多个原点

© www.soinside.com 2019 - 2024. All rights reserved.