首页 > 解决方案 > django-push-notification 401 未经授权

问题描述

我正在尝试使用django-push-notifications设置推送通知,我已经复制了示例中的大部分代码。我有一个调用该enablePushNotifications()函数的按钮:

export function enablePushNotifications() {
    console.log("enabling push notifications...");
    if (!'serviceWorker' in navigator){
        console.log("Push notifications not supported");
        return;
    }
    navigator.serviceWorker.ready.then(
        (registration)=>{
            registration.pushManager.subscribe({
                userVisibleOnly: true
            }).then(
                (sub)=>{
                    console.log(sub);
                    let endpointParts = sub.endpoint.split("/");
                    let registration_id = endpointParts[endpointParts.length - 1];
                    let data = {
                        'browser': loadVersionBrowser(navigator.userAgent).name.toUpperCase(),
                        'p256dh': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))),
                        'auth': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth')))),
                        'registration_id': registration_id,
                        'endpoint': sub.endpoint,
                    };
                    request(
                        "/api/subscribe",
                        data
                    )
                }
            ).catch(
                (error)=>console.error(error)
            )
        }
    )
}

当我打开网络选项卡时,我看不到传递的属性或标题有任何奇怪之处。具体而言,该browser值是正确的。URL的实现/api/subscribe如下:

import push_notifications.models as pushmodels
def registerPush(request):
    data = requestFormatting.get_data(
        request
    )

    device = pushmodels.WebPushDevice(
        name=request.user.username,
        active=True,
        user=request.user,
        registration_id=data["registration_id"],
        p256dh=data["p256dh"],
        auth=data["auth"],
        browser=data["browser"]
    )

    device.save()

    device.send_message("hello")

调用此函数会引发 PushError: Push failed: 401 Unauthorized。我已经在 chrome 和 firefox 上进行了测试,两者都给出了相同的错误。我指定了我FCM_API_KEY的设置,没有别的。我目前不使用 VAPID,但我计划在未来使用。我尝试了代码的各种变体,但似乎没有任何效果。文档不清楚如何实际初始化设备,我只选择了一个WebPushDevice对象,因为它似乎包含与示例中提供的数据相似的属性。

这是我第一次尝试使用网络推送,因此非常感谢您的帮助!

标签: pythondjangoweb-pushdjango-push-notifications

解决方案


推荐阅读