Firebase Storage跨域问题:预检请求未通过HTTP OK状态校验
Firebase Storage 上传图片遇CORS错误及文件未上传问题解决
问题描述
Chrome控制台报错:
从源'http://localhost:5173'访问XMLHttpRequest至'https://firebasestorage.googleapis.com/v0/b/%22website-admin-c9ce6.appspot.com%22VITE_APP_VERSION%3D0.0.0/o/MYx2YMuRBwTD1YBzm3UgpV4bpMx1%2F7D45367D-6184-415C-BFC2-9FE85B5D031B.jpeg'已被CORS策略阻止:对预检请求的响应未通过访问控制检查:没有HTTP OK状态。
已尝试的CORS配置步骤:
- 创建
cors.json文件,内容如下:
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
- 执行命令:
gsutil cors set cors.json gs://website-admin-c9ce6.appspot.com,命令输出Setting CORS on gs://website-admin-c9ce6.appspot.com/...,但问题依旧,图片也未出现在Firebase控制台。
调用Storage的代码:
const storage = getStorage(); export class StorageClient { async uploadFile(file: File) { try { const fileRef = ref(storage, `${authStore.user!.uid}/${file.name}`) const url = await getDownloadURL(fileRef); return new DbEditResponse(DbEditStatus.success, url) } catch (e) { return new DbEditResponse(DbEditStatus.error, 'Error. Did not upload file.') } } }
解决方法
1. 修复代码核心逻辑错误
当前代码仅创建了文件引用,直接调用getDownloadURL,但完全没有执行文件上传操作,这是图片未出现在控制台的根本原因。必须先通过uploadBytes完成文件上传,再获取下载链接:
修正后的代码:
const storage = getStorage(); export class StorageClient { async uploadFile(file: File) { try { const fileRef = ref(storage, `${authStore.user!.uid}/${file.name}`); // 先执行上传操作 await uploadBytes(fileRef, file); // 上传完成后再获取下载URL const url = await getDownloadURL(fileRef); return new DbEditResponse(DbEditStatus.success, url); } catch (e) { console.error("上传失败详情:", e); return new DbEditResponse(DbEditStatus.error, 'Error. Did not upload file.'); } } }
2. 更新CORS配置方法权限
当前CORS配置仅允许GET方法,但上传操作需要POST、PUT等方法支持,更新cors.json:
[ { "origin": ["http://localhost:5173"], "method": ["GET", "POST", "PUT", "DELETE"], "maxAgeSeconds": 3600 } ]
重新执行gsutil cors set cors.json gs://website-admin-c9ce6.appspot.com,确保配置生效。
3. 排查存储桶地址拼接错误
从报错URL可以看到,存储桶名称被错误混入了VITE_APP_VERSION%3D0.0.0,这说明Firebase初始化时存储桶配置存在变量拼接错误。检查初始化代码,确保存储桶名称正确:
// 正确的初始化示例 const app = initializeApp({ storageBucket: "website-admin-c9ce6.appspot.com" }); const storage = getStorage(app);
内容的提问来源于stack exchange,提问作者Jacob Miller
相关产品推荐
相关产品推荐

