从Nuxt.js调用Firebase Cloud Function出现CORS错误求助
我编写了一段测试用的简单代码,但运行时出现CORS跨域错误。是否是因为使用了POST请求导致的?我尝试了各种方法但都没有解决。
我已在云控制台测试过该Firebase函数,确认功能正常,因此怀疑是Nuxt.js的fetch函数存在问题导致错误。恳请各位提供帮助。
Firebase函数Node.js代码(index.js)
const admin = require("firebase-admin"); const functions = require("firebase-functions"); // Allow cross-origin requests const cors = require("cors")({ origin: true, }); admin.initializeApp(); exports.askQuestionIntent = functions.https.onRequest(async (req, res) => { return cors(req, res, async () => { console.log("yeeeeeee") }); });
前端Nuxt.js调用代码(store文件)
export const actions = { async askQuestion({ commit, state }, value) { console.log(value); const firebaseRest = "https://us-central1-abc.cloudfunctions.net/askQuestionIntent"; let res = await fetch(firebaseRest, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(messagePrompts), }); let data = await res.json(); console.log(data); }, };
控制台错误信息
Access to fetch at 'https://us-central1-abc.cloudfunctions.net/askQuestionIntent' from origin 'https://www.mysite.app' 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.
POST https://us-central1-abc.cloudfunctions.net/askQuestionIntent net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
问题核心不是POST请求本身,而是Firebase函数未正确返回响应,导致CORS头无法正常设置,同时要确保预检请求被正确处理。
1. 修复Firebase函数代码
函数内部必须给客户端返回响应,否则请求会超时,CORS中间件无法完成头信息设置:
const admin = require("firebase-admin"); const functions = require("firebase-functions"); const cors = require("cors")({ origin: true, // 允许所有域名跨域,如需限制可改为具体域名如"https://www.mysite.app" }); admin.initializeApp(); exports.askQuestionIntent = functions.https.onRequest(async (req, res) => { return cors(req, res, async () => { console.log("yeeeeeee"); // 必须返回响应,示例返回JSON格式内容 res.status(200).json({ success: true, message: "请求已处理" }); }); });
2. 优化前端Nuxt.js代码
- 确保
messagePrompts变量已定义,避免JSON序列化报错 - 添加错误捕获,方便排查问题:
export const actions = { async askQuestion({ commit, state }, value) { console.log(value); const firebaseRest = "https://us-central1-abc.cloudfunctions.net/askQuestionIntent"; try { // 确认messagePrompts存在,替换为实际要发送的数据 const payload = messagePrompts || {}; let res = await fetch(firebaseRest, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }); // 检查HTTP响应状态 if (!res.ok) { throw new Error(`请求失败,状态码:${res.status}`); } let data = await res.json(); console.log(data); } catch (error) { console.error("请求出错:", error); } }, };
3. 必要的后续操作
- 重新部署函数:修改代码后执行
firebase deploy --only functions,确保最新代码生效 - 查看函数日志:在Firebase控制台查看函数是否被触发,有没有内部报错
- 验证CORS配置:如果需要限制域名,将
origin: true改为你的前端域名"https://www.mysite.app",提升安全性
内容的提问来源于stack exchange,提问作者Remo Bajwa

