You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js开发Firebase安卓聊天App推送通知,部署遇正则解析错误

解决Firebase云函数部署的正则解析错误及代码问题

嘿,作为Node.js新手碰到这种云函数报错太正常了,我帮你梳理下代码里的细节问题,修正后就能正常部署了:

核心报错原因

你看到的Parsing error: Invalid regular expression flag,是因为你错误地用了正则表达式的斜杠/来拼接数据库路径,Node.js里拼接动态路径应该用模板字符串(反引号``),不是斜杠语法。

代码里的具体问题&修复点

  1. 变量名不匹配:
    你定义了const notification = event.params.notification;,但函数路径里的参数是notification_id,后面代码里又用到了未定义的notification_id变量,这里要把变量名统一改成notification_id。

  2. 数据库路径&查询语法错误:
    原代码里的const fromUser = admin.database().ref(/notification/${user_id}/{notification_id}).once(value);完全写错了:

    • 动态路径必须用反引号包裹,占位符统一用${}格式
    • once()的参数必须是字符串'value',不是未定义的value变量
  3. 冗余的用户查询路径:
    你原代码里查/Users/${user_id}/${notification_id}是错误的,应该查询发送请求的用户信息,路径调整为/Users/${from_user_id}才能获取到发起请求的用户名。

修复后的完整代码

'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite(event => {
  const user_id = event.params.user_id;
  // 修正变量名,和路径参数保持一致
  const notification_id = event.params.notification_id; 
  console.log("The User Id is : ", user_id);

  if (!event.data.val()) {
    // 变量已定义,可正常使用
    return console.log('A Notification has been deleted from database : ', notification_id); 
  }

  // 修复路径语法:用模板字符串,once参数改为'value'
  const fromUserRef = admin.database().ref(`/notification/${user_id}/${notification_id}`).once('value');
  return fromUserRef.then(fromUserResult => {
    const from_user_id = fromUserResult.val().from;
    console.log('You have new notification from : ', from_user_id);

    // 修正用户查询路径:获取发送请求的用户信息
    const userQuery = admin.database().ref(`/Users/${from_user_id}`).once('value');
    return userQuery.then(userResult => {
      const userName = userResult.val().name; // 假设用户数据里有name字段,可根据你的数据库结构调整
      const deviceTokenRef = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
      return deviceTokenRef.then(result => {
        const token_id = result.val();
        const payload = {
          notification: {
            title: "Friend Request",
            body: `${userName} has sent you a request`,
            icon: "default"
          }
        };
        return admin.messaging().sendToDevice(token_id, payload);
      });
    });
  });
});

部署步骤

修正代码后,先在functions目录下运行npm run lint确认没有语法错误,再执行firebase deploy --only functions就能正常部署了。

内容的提问来源于stack exchange,提问作者Ouneeb Ur Rehman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:50:16