生产环境React-PDF加载Firebase Storage PDF遇CORS跨域问题求助
生产环境React-PDF加载Firebase存储PDF触发CORS错误解决方案
问题说明
本地及开发环境中,使用React-PDF加载Firebase存储的PDF文档可正常运行,但生产环境下请求该PDF时触发CORS错误,提示目标资源缺少Access-Control-Allow-Origin响应头。
相关代码
import React, { useState } from 'react'; import { pdfjs, Document, Page } from 'react-pdf'; import useWindowSize from 'hooks/useWindowSize'; pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`; const options = { cMapUrl: '/cmaps/', standardFontDataUrl: '/standard_fonts/', httpHeaders: { Origin: 'https://app.e-english.com.au' } }; export const ReactPdf = (props) => { const { url } = props; const [numPages, setNumPages] = useState(); const [width] = useWindowSize(); const onDocumentLoadSuccess = ({ numPages: nextNumPages }) => { setNumPages(nextNumPages); }; console.log('PDF URL:', url); const pdfUrl = 'https://firebasestorage.googleapis.com/v0/b/eng-tutor-app.appspot.com/o/materials%2Fmock%2FDemo%20Lesson%20Plan%20-%20Tutor%20Training.pdf?alt=media&token=9442249d-6bca-41d9-ad3e-83e6e4250349'; return ( <Document file={{ url: pdfUrl }} onLoadSuccess={onDocumentLoadSuccess} loading={'loading'} options={options}> {Array.from(new Array(numPages), (el, index) => ( <Page key={`page_${index + 1}`} pageNumber={index + 1} width={width < 500 ? width - 10 : width} height={422} scale={1} /> ))} </Document> ); };
错误信息
call:1 Access to fetch at 'https://firebasestorage.googleapis.com/v0/b/eng-tutor-app.appspot.com/o/materials%2Fmock%2FDemo%20Lesson%20Plan%20-%20Tutor%20Training.pdf?alt=media&token=9442249d-6bca-41d9-ad3e-83e6e4250349' from origin 'https://app.e-english.com.au' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. build.umd.js:1233 GET https://firebasestorage.googleapis.com/v0/b/eng-tutor-app.appspot.com/o/materials%2Fmock%2FDemo%20Lesson%20Plan%20-%20Tutor%20Training.pdf?alt=media&token=9442249d-6bca-41d9-ad3e-83e6e4250349 net::ERR_FAILED 200 (OK)
解决方案
方案1:配置Firebase Storage的CORS规则(推荐)
从根源解决跨域问题,允许生产域名访问Firebase存储资源:
- 本地创建
cors.json文件,写入以下配置:
[ { "origin": ["https://app.e-english.com.au"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
- 确保已安装Firebase CLI并登录,执行命令将配置上传到目标存储桶:
gsutil cors set cors.json gs://eng-tutor-app.appspot.com
注意:替换gs://eng-tutor-app.appspot.com为你实际的Firebase存储桶地址
方案2:通过后端代理转发PDF请求
若暂时无法修改Firebase配置,可通过后端代理绕过浏览器CORS检查:
- 后端示例(Node.js + Express):
// 需先安装依赖:npm install express node-fetch const express = require('express'); const fetch = require('node-fetch'); const app = express(); app.get('/proxy-pdf', async (req, res) => { try { const pdfUrl = decodeURIComponent(req.query.url); const response = await fetch(pdfUrl); const buffer = await response.buffer(); res.setHeader('Content-Type', 'application/pdf'); res.send(buffer); } catch (error) { res.status(500).send('PDF加载失败'); } }); app.listen(3001, () => console.log('代理服务启动于3001端口'));
- 前端修改React-PDF的请求地址为代理接口:
const pdfUrl = '/proxy-pdf?url=' + encodeURIComponent('https://firebasestorage.googleapis.com/...你的PDF完整地址...');
环境差异原因
本地开发环境通常借助webpack-dev-server的代理功能,或浏览器对localhost域名的CORS策略较为宽松,不会触发严格检查;生产环境使用正式域名,浏览器会严格执行CORS规则,因此出现错误。
内容的提问来源于stack exchange,提问作者Sohaib Ashraf
相关产品推荐
相关产品推荐

