Firebase Functions与Angular部署后的CORS跨域问题排查及解决
Firebase Functions部署NestJS后CORS错误解决记录
我有一个Firebase项目,架构为:NestJS应用部署至Firebase Functions,Angular应用部署至Firebase Hosting,同时使用Firebase Realtime Database。遇到的问题是:部署后或本地运行的Angular调用Functions接口时触发CORS错误,但用Postman或直接在浏览器打开接口URL可正常获取数据。
报错信息
Access to fetch at 'https://us-central1-my-project-name.cloudfunctions.net/api/endpoint/' from origin 'https://my-project-name.firebaseapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
已尝试的解决方案
NestJS服务端配置尝试
在main.ts中尝试了三种CORS配置,均无效:
- 方案1:指定具体来源、方法和允许的请求头
async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors({ origin: 'https://my-project-name.firebaseapp.com/', methods: 'GET, PUT, POST, DELETE', allowedHeaders: 'Content-Type, Authorization', }); await app.listen(3000); } bootstrap();
- 方案2:启用默认CORS配置
async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); } bootstrap();
- 方案3:创建应用时直接启用CORS
async function bootstrap() { const app = await NestFactory.create(AppModule, { cors: true }); await app.listen(3000); } bootstrap();
请求端尝试
分别使用Angular HTTP Client、Axios、fetch API发起请求,结果均返回相同CORS错误。还尝试过添加请求头和修改请求模式:
- 手动添加
Access-Control-Allow-Origin头
fetch('https://us-central1-my-project-name.cloudfunctions.net/api/endpoint/', { mode: 'cors', headers: { 'Access-Control-Allow-Origin': '*' } }) .then(response => response.json()) .then(json => console.log(json))
- 设置
no-cors模式
fetch('https://us-central1-my-project-name.cloudfunctions.net/api/endpoint/', { mode: 'no-cors' }) .then(response => response.json()) .then(json => console.log(json))
以上请求端调整均未解决问题。
后续更新与最终解决
更新1
移除所有自定义请求头,简化fetch请求:
fetch('https://us-central1-my-project-name.cloudfunctions.net/api/endpoint/') .then(response => response.json()) .then(json => console.log(json))
同时更新main.ts的CORS配置,添加本地开发地址:
async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors({ origin: ['https://my-project-name.firebaseapp.com', 'http://localhost:4200'], methods: 'GET, PUT, POST, DELETE', allowedHeaders: 'Content-Type, Authorization', }); await app.listen(3000); } bootstrap();
但错误依旧存在。
更新2
查看浏览器Network tab,确认预检OPTIONS请求未返回正确的CORS响应头。
更新3:问题根源与解决
最终发现核心问题:NestJS项目根目录同时存在main.ts和index.ts文件,而Firebase Functions实际加载的是index.ts,导致main.ts中的CORS配置完全没有生效。
解决步骤:
- 删除
main.ts文件 - 将方案2的CORS配置迁移到
index.ts中 - 重新部署Firebase Functions
部署完成后,Angular调用接口的CORS错误消失。
内容的提问来源于stack exchange,提问作者user14451038
相关产品推荐
相关产品推荐

