[英]WebPush.sendNotification Node.js giving 401 "header must be specified" error on googleapis endpoint
我收到以下錯誤:
WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/Users/sepp/.../node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (node:events:406:35)
at endReadableNT (node:internal/streams/readable:1331:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
statusCode: 401,
headers: {
'content-type': 'text/plain; charset=utf-8',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0',
date: 'Wed, 01 Feb 2023 19:57:43 GMT',
'content-length': '40',
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
connection: 'close'
},
body: 'authorization header must be specified.\n',
endpoint: 'https://fcm.googleapis.com/fcm/send/duj-etc-etc
涉及的代碼是:
import * as webPush from "web-push";
const subDetails = {
endpoint: "https://fcm.googleapis.com/fcm/send/duja6etc-etc",
expirationTime: null,
keys: {
p256dh: "BHtwM-etc-etc",
auth: "aYkx0etc-etc"
}
}
await webPush.sendNotification(subDetails, "test message", );
我是在Github上發現這個問題的,有些郁悶是不是跟環境有關。 我在本地運行我的前端頁面和后端服務器。 響應中有一個'x-frame-options': 'SAMEORIGIN'
header。
從上面的代碼可以看出,我沒有設置 VAPID 。
如果我使用console.log(webPush.generateRequestDetails(pushSub.details, args.msg))
查看請求的標頭和正文是什么,我會得到以下詳細信息,這表明未設置身份驗證 header:
{
method: 'POST',
headers: {
TTL: 2419200,
'Content-Length': 121,
'Content-Type': 'application/octet-stream',
'Content-Encoding': 'aes128gcm'
},
body: <Buffer ....>,
endpoint: 'https://fcm.googleapis.com/fcm/send/duj-etc-etc'
}
編輯:我使用的瀏覽器是Opera GX 。 我確實找到了一個瀏覽器支持表,上面說 opera 還不支持桌面上的推送。 該錯誤似乎仍然暗示其他問題可能是問題所在。 在Firefox Dev Edition中測試,它有效,不幸的是,在Chrome中給出了與 Opera GX 完全相同的錯誤。
這個問題有兩個方面。
問題 #1: Opera GX 不支持桌面上的推送通知。 查看此表以了解有關您的瀏覽器的詳細信息。
問題 #2:對於使用https://fcm.googleapis.com/fcm/send/
端點的任何推送服務,您都需要授權標頭。 要創建它們,您需要一個 VAPID。 以下是在web-push
中設置它的方法:
$ web-push generate-vapid-keys --json
import * as webPush from "web-push"; const subDetails = { endpoint: "https://fcm.googleapis.com/fcm/send/duja6etc-etc", expirationTime: null, keys: { p256dh: "BHtwM-etc-etc", auth: "aYkx0etc-etc" } } const VAPID = { publicKey: "lalalla-etc-etc-put-anywhere", privateKey: "lCRVkwS-etc-etc-put-somewhere-safe" } const parsedUrl = new URL(subDetails.endpoint); const audience = `${parsedUrl.protocol}//${parsedUrl.hostname}`; // technically, the audience doesn't change between calls, so this can be cached in a non-minimal example const vapidHeaders = webPush.getVapidHeaders( audience, 'mailto: example@web-push-node.org', VAPID.publicKey, VAPID.privateKey, 'aes128gcm' ); await webPush.sendNotification(subDetails, "test msg", { headers: vapidHeaders });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.