尝试使用 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.
详情:
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": ["*"]
}
]
"AllowedOrigins": [
"http://localhost:5173",
"http://localhost:5174"
]
试试这个