Firebase Hosting调用Cloud Functions遇CORS拦截,跨设备推送失败
解决Firebase Cloud Functions的CORS重定向错误
嘿,我看你遇到的这个CORS错误,核心问题其实是请求的云函数路径不匹配,再加上代码里的几个小疏漏,导致预检请求触发了重定向限制。下面一步步帮你解决:
1. 先搞定路径不匹配的问题
你看,你的云函数导出的是notification(单数):
exports.notification = functions.https.onRequest((req, res) => { ... })
但客户端请求的是notifications(复数):
fetch("https://[zone]-[project].cloudfunctions.net/notifications", ...)
这种不匹配会让Firebase返回404,然后自动重定向到错误页面,而浏览器的预检OPTIONS请求是不允许重定向的,这就直接触发了CORS报错。
修复方法:要么把云函数的导出名改成notifications,要么把客户端的请求路径改成notification,两边保持一致就行。
2. 修复云函数里未定义的notification变量
你的云函数里直接用了notification变量,但这个变量根本没从请求体里取,运行起来肯定报错。得从req.body里读取客户端发过来的token和notification数据才行。
修改后的完整云函数代码:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); const cors = require('cors')({ origin: true }); admin.initializeApp(); // 这里改成notifications,和客户端请求路径一致 exports.notifications = functions.https.onRequest((req, res) => { return cors(req, res, () => { if (req.method === "POST") { // 从请求体里拿到客户端发送的token和通知内容 const { token, notification } = req.body; // 按照FCM要求构造消息格式,必须指定接收的token const message = { token: token, notification: notification }; return admin.messaging().send(message) .then(result => { console.log('推送成功:', result); res.status(200).send("ok") }) .catch(err => { console.error('推送失败:', err); res.status(500).send(err.message); }); } else { return res.status(400).send("Method not allowed"); } }); });
3. 确认客户端请求格式正确
要确保你调用send方法时,notification参数包含FCM要求的字段,比如title和body,举个例子:
// 调用send的示例代码 this.send({ title: "新消息提醒", body: "来自另一台设备的推送通知" }, targetDeviceToken);
4. 重新部署云函数
改完代码后,别忘了重新部署你的云函数:
firebase deploy --only functions:notifications
做完这些步骤,那个CORS重定向的错误应该就消失了,推送通知也能正常发送啦!
内容的提问来源于stack exchange,提问作者lucasmenendez
相关产品推荐
相关产品推荐

