我正在尝试在react和django中实现推送通知。遵循developer google push-notifications的推送通知文档。能够生成订阅密钥并将其存储到数据库中。在后端,我正在使用django,因此我使用pywebpush库。创建订阅后,我将其保存到数据库中。成功存储数据后,我是与message相同的数据,并称为函数webpush。我收到响应201,但我没有收到任何通知。
注意:为了做出反应,我使用了creact-react-app并尝试在开发环境中实现推送通知。我在public / sw.js中创建了单独的sw.js文件。从开发工具中,我可以触发推送通知,但是从代码中,我无法触发它。
在此先感谢您的帮助。
Django:
class trigger_notification (generics.CreateAPIView):
"""
API Endpoint to trigger the notification
"""
serializer_class = UserSubscriptionSerializer
def post(self, request):
try:
data = request.data
print('Came to trigger push service')
# Get the subscription and data to be send
trigger_notification = webpush(
subscription_info={
'endpoint': data['endpoint'],
'keys': {
'p256dh': data['p256dh'],
'auth': data['auth']
}
},
data=data['message'],
vapid_private_key=config('PRIVATE_KEY'),
vapid_claims={
"sub" : "mailto:admin@xyz.com"
}
)
print('Trigger Notification -------')
print(trigger_notification)
print('end---------------- ')
return Response({'message' : 'trigger push notification'}, status=201)
except WebPushException as e:
# Print the error
print("Error occurred while web push:", repr(e))
return Response({'error' : 'Error occurred to trigger notification:' + repr(e) }, status=500)
反应:
function registerValidSW(swUrl, config)
{
navigator.serviceWorker
.register(swUrl)
.then(registration => {
// Ask permission if user is not subscribed for notification
if (Notification.permission === 'default')
{
// Ask permission, get permission and trigger notification of user has
// been subscribed.
askPermission()
.then((res) => {
subscribeToPush()
.then(pushSubscription => {
const subscriptionObj = JSON.stringify(pushSubscription);
// Save the subscription data of user
sendSubscriptionToBackEnd(subscriptionObj)
.then(res => {
console.log('On successful insertion:', res);
// Trigger the notification to thank user
res.data['message'] = 'Thanks for subscribing.' +
'We will keep you updated with future operation.';
console.log('About to trigger the push service')
// Trigger the push notification
const triggerNotification = axios.post(
'/api/trigger_notification/',
res.data
);
triggerNotification
.then(res => console.log('Trigger Notification(success):', res))
.catch(err => console.log('Trigger notification(error):', err))
})
.catch(err => console.log('Sending Subscription(error):', err));
})
});
}
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if ( installingWorker == null )
{
return;
}
installingWorker.onstatechange = () => {
if ( installingWorker.state === 'installed' )
{
if ( navigator.serviceWorker.controller )
{
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.
);
// Execute callback
if ( config && config.onUpdate )
{
config.onUpdate(registration);
}
}
else
{
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if ( config && config.onSuccess )
{
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => console.error('Error during service worker registration:', error));
}