React用预签名URL上传文件到CloudFlare R2遇CORS预检错误
使用预签名URL向CloudFlare R2存储上传文件时的CORS错误
在基于Axios的React应用中,通过预签名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/和*。 - 已在
AllowedMethods中添加所有必要方法(PUT、GET、POST)。 - 尝试过为
AllowedHeaders和ExposeHeaders设置多种不同值。 - 也调整过
MaxAgeSeconds的数值。
当前R2 CORS配置
[ { "AllowedOrigins": [ // 已尝试设置为"*" "http://localhost:5173/", "http://localhost:5174/" ], "AllowedMethods": [ // 已尝试设置为"*" "PUT", "GET", "POST" ], "AllowedHeaders": [ // 已尝试设置为"*" "x-requested-by", "User-Agent", "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Type", "Expires" ], "ExposeHeaders": [ // 已尝试设置为"*" "Content-Encoding", "cf-cache-status", "Date" ], "MaxAgeSeconds": 3600 // 已尝试设置多个不同数值 } ]
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
尝试过的简化CORS配置
[ { "AllowedOrigins": ["*"], "AllowedMethods": ["*"], "AllowedHeaders": ["*"], "ExposeHeaders": ["*"] } ]
已在网上大量搜索但未找到解决方案,恳请提供帮助!
内容的提问来源于stack exchange,提问作者Nazir Mudumane
相关产品推荐
相关产品推荐

