在我的 Next.js 应用程序中,我希望能够从请求正文中获取 iOS 设备令牌,并在有人点击我在我的/pages/api/sendPushNotification.ts
. 我正在使用node-apn
包(https://www.npmjs.com/package/apn)在我的 Node.js 服务器代码(位于pages/api/sendPushNotification.ts
)和 Apple 推送通知服务之间建立连接。我已经有了我的.p8 key file
,我知道它可能不应该被提交,但我想不出任何其他方式来传递它的路径。我有它位于/public/apn/AuthKey.p8
。当我将本地绝对路径从包传递.p8 key file
到此配置时,本地一切正常:node-apn
var options = {
token: {
key: "path/to/APNsAuthKey_XXXXXXXXXX.p8",
keyId: "key-id",
teamId: "developer-team-id"
},
production: true
};
但是,在 Vercel 上将我的项目部署到生产环境后,.p8 key file
找不到,我总是收到一条错误消息:
VError: Failed loading token key: ENOENT: no such file or directory, open '/apn/AuthKey.p8'
我遵循了本教程: https ://medium.com/@boris.poehland.business/next-js-api-routes-how-to-read-files-from-directory-compatible-with-vercel-5fb5837694b9 尝试实现它但没有成功。
我里面的代码/pages/api/sendPushNotification.ts
是这样的:
const apn = require("apn");
import fs from "fs";
import path from "path";
export default async (req, res) => {
const dirRelativeToPublicFolder = "apn";
const dir = path.resolve("./public", dirRelativeToPublicFolder);
const filename = fs.readdirSync(dir);
const authKey = path.join("/", dirRelativeToPublicFolder, filename[0]);
const { iosTokens } = req.body;
res.statusCode = 200;
res.json({
message: "Notification sent!",
});
if (iosTokens?.length !== 0) {
const apnOptions = {
token: {
key: authKey,
keyId: process.env.NEXT_PUBLIC_APN_KEY_ID,
teamId: process.env.NEXT_PUBLIC_APN_TEAM_ID,
},
production: true,
};
const apnProvider = new apn.Provider(apnOptions);
const note = new apn.Notification();
note.alert = {
title: "XXXXX",
body: "XXXXXXXXXX",
};
note.sound = "default";
note.topic = "XXXXXXX";
console.log(
`Attempting to send the notification to ${iosTokens.length} iOS devices.`
);
iosTokens.forEach((deviceToken) => {
apnProvider
.send(note, deviceToken)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(
"Error occured when trying to send notification: ",
error
);
});
});
}
}