使用预签名 URL 上传文件时 CORS 错误 (React/CloudFlare R2) - 预检响应问题

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

尝试使用 React 应用程序(使用 Axios)中的预签名 URL 将文件上传到 CloudFlare R2 存储时遇到 CORS 错误。在Postman中上传工作正常,但浏览器抛出以下错误:

Access to XMLHttpRequest at 'https://<bucketName>.<accountID>.r2.cloudflarestorage.com/...' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

详情:

  • 我已经尝试在我的 CloudFlare CORS 配置中将
    AllowedOrigins
    设置为
    http://localhost:5173/
    *
  • 我已在
    PUT
    中包含了所有必要的方法(
    GET
    POST
    AllowedMethods
    )。
  • 我尝试了
    AllowedHeaders
    ExposeHeaders
    的各种值。
  • MaxAgeSeconds
    也已调整为不同的值。

我当前的 R2 CORS 配置:

[
 {
  "AllowedOrigins": [ // I already tried putting "*"
   "http://localhost:5173/",
   "http://localhost:5174/"
  ],
  "AllowedMethods": [ // I already tried putting "*"
   "PUT",
   "GET",
   "POST"
  ],
  "AllowedHeaders": [ // I already tried putting "*"
   "x-requested-by",
   "User-Agent",
   "Cache-Control",
   "Content-Disposition",
   "Content-Encoding",
   "Content-Language",
   "Content-Type",
   "Expires"
  ],
  "ExposeHeaders": [ // I already tried putting "*"
   "Content-Encoding",
   "cf-cache-status",
   "Date"
  ],
  "MaxAgeSeconds": 3600 // I already tried putting many numbers
 }
]

我在网上进行了大量搜索,但没有找到解决方案。任何帮助将不胜感激!

我的 React 应用程序:

import axios from 'axios';
function App() {
  const onFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const { files } = event.target
    if (files) {
      const file = files[0]

      const uploadLink = await api
        .post('/upload', { filename: file.name, contentType: file.type })
        .then(({ data }) => data.links.uploadURL)

      console.log({ uploadLink })

      await axios
        .put(uploadLink, file)
        .then(() => window.alert('file uploaded'))
        .catch((err) => {
          console.log('failed to upload file:')
          console.error(err)
        })
    }
  }

  return (
    <div className="w-screen h-screen flex items-center justify-center">
      <input type="file" onChange={onFileChange} />
    </div>
  )
}

export default App
[
 {
  "AllowedOrigins": ["*"],
  "AllowedMethods": ["*"],
  "AllowedHeaders": ["*"],
  "ExposeHeaders": ["*"]
 }
]
cors pre-signed-url cloudflare-r2
1个回答
0
投票
"AllowedOrigins": [ 
   "http://localhost:5173",
   "http://localhost:5174"
  ]

试试这个

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