如何为Parse Server配置推送通知?找不到index.js文件求助
一、定位Parse Server的配置文件/启动脚本
你找不到index.js,大概率是因为采用全局npm安装的Parse Server(即通过npm install -g parse-server安装),这种方式默认没有本地index.js,而是通过命令行参数或config.json完成配置。可按以下步骤处理:
查找全局Parse Server安装路径
执行命令:which parse-server输出类似
/usr/local/bin/parse-server,对应的核心安装目录一般为/usr/local/lib/node_modules/parse-server,里面有官方示例index.js可参考。两种配置方案选择
方案1:修改现有
config.json添加推送配置
打开home目录下的config.json,在根节点插入推送相关配置(以FCM为例):{ "appId": "你的AppID", "masterKey": "你的MasterKey", // 保留原有其他配置 "push": { "android": { "senderId": "你的FCM Sender ID", "apiKey": "你的FCM Server Key" } } }修改完成后重启Parse Server即可生效。
方案2:创建自定义
index.js启动脚本
在home目录新建index.js,参考官方示例编写配置,这种方式更灵活,便于后续添加数据变更触发器:const ParseServer = require('parse-server').ParseServer; const path = require('path'); const api = new ParseServer({ databaseURI: 'mongodb://localhost:27017/parse', // 替换为你的数据库地址 cloud: path.join(__dirname, '/cloud/main.js'), // 云函数目录,无则先创建 appId: '你的AppID', masterKey: '你的MasterKey', serverURL: 'http://你的服务器IP:1337/parse', push: { android: { senderId: '你的FCM Sender ID', apiKey: '你的FCM Server Key' } } }); // 启动服务器 const http = require('http'); const server = http.createServer(); server.listen(1337, function() { console.log('Parse Server running on http://你的服务器IP:1337/parse'); }); server.on('request', api);之后用
node index.js启动(或nohup node index.js &后台运行),替代原全局命令启动方式。
二、配置数据变更触发通知
要实现数据库值变更时推送通知,需借助Parse的云函数触发器:
创建云函数目录
在home目录执行命令:mkdir cloud && touch cloud/main.js编写触发通知的云函数
以监听User类数据更新为例,当用户数据变更时推送通知:Parse.Cloud.afterUpdate('User', async (request) => { const query = new Parse.Query(Parse.Installation); query.equalTo('user', request.object); // 关联目标用户的设备 const payload = { alert: '你的账户信息已更新', // 可选自定义数据 data: { type: 'user_update', userId: request.object.id } }; try { await Parse.Push.send({ where: query, data: payload }); console.log('推送通知发送成功'); } catch (error) { console.error('推送通知发送失败:', error); } });若需监听其他类,将
User替换为对应类名即可。重启Parse Server
修改云函数后,必须重启Parse Server才能生效。
三、验证配置
- 测试服务器推送配置
通过Parse Dashboard的Push功能手动发送测试通知,确认Android设备能否接收。 - 验证数据变更触发
修改目标类的数据库数据,查看服务器日志(logs目录或nohup.out)是否有推送成功记录,同时检查Android设备是否收到通知。
内容的提问来源于stack exchange,提问作者edgar_wideman

