使用 React 的 AWS CDN 上的 CORS 问题

CORS issue on AWS CDN with React

我正在尝试从已部署的 React 应用程序 (AWS S3 CDN) 调用 grails 应用程序上的资源。

React 应用有 ULR https://something.cloudfront.net/index.html

CORS 配置看起来与 AWS guide 上的一样,当然除了 exemple.com。

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>https://example.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <ExposeHeader>ETag</ExposeHeader>
    <ExposeHeader>x-amz-meta-custom-header</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Grails 应用程序配置 (application.yml) 如下所示:

grails:
  cors:
    enabled: true
    allowedOrigins:
    - "https://something.cloudfront.net"

完成所有这些设置后,我在浏览器中收到消息:

Failed to load https://example.com/someResources: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:52449' that is not equal to the supplied origin. Origin 'https://something.cloudfront.net' is therefore not allowed access.

我很纳闷为什么我看到http://localhost:52449? I have built the react application and copy the static file into the CDN, http://localhost:52449是本地用npm start启动react app的地址。

进行 rest 调用的 React 代码如下所示:

axios.get<any>('https://example.com/someResources',
    {
        withCredentials: true,
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Requested-With": "XMLHttpRequest"
        },
    })
    .then((response) => 
        console.log(response);
    );

编辑 1:

我做错了什么,CORS 问题仍然存在?

您可以将 AllowedOrigin 永久设置为 *

但是你需要根据你的react应用域设置一个有效值

能否粘贴网络调试器 Request/Response Headers? 请确保在 PreFlight Request Header 中发送的 Request Header 中可以看到的 1-Origin 应与 1-Access-Control-Allow-Origin”。还有你根据请求调用的 HTTP 方法,header 明智和动词明智 2-"Access-Control-Request-Headers" & 3-"Access-Control-Request-Method" 应符合 Response Header 参数:2-"Access-Control-Allow-Headers" 和 3-"Access-Control-Allow-Methods" 在响应中。否则 Pre-flight(OPTION) 请求将失败。

可能您的浏览器正在缓存页面。这就是为什么如果您从网络调试模式而不是控制台追溯它,您可以更轻松地追溯问题。 Pre-Flight Network Debugging on Chrome

我为此纠结了好几天! React AWS API 和 COR。

此时我正在使用 fetch 和 axios。

答案是把所有headers都取出来。到处都说 headers 是服务器端的东西。报告的错误似乎是 CORS / 预检,解决方案在于 Options 过程。我尝试了一切,今天早上我删除了 API,用每个选项重建它以打开 CORS,然后剥离我的代码 headers 和变量,而是加载一个 URL 到看看我是否可以通过并查看我会遇到的错误类型。 None!这是代码:

axios.post(postUrl).then(
  (res) => {
    console.log('Axios:',res);
    console.log('Axios data:',res.data);
  }
).catch((err) => {
  console.log('Axios Error:', err);
})

fetch(postUrl, {
      method: 'POST'
    }).catch(error => console.log('fetch',error))

fetch 也有效 'naked'。我更喜欢 axios,因为结果是用数据来安慰的。如果可能的话,我没有解决 fetch 问题。我知道 fetch 与旧浏览器有关。

其中 postUrl 是用于在浏览器中测试 API 的 URL。

我现在只需要编写代码来动态构建 URL,这应该很容易。著名遗言...