1

请解释如何使用 XHR 和 Javascript 进行推送通知。或者是否有任何其他方式可以在渐进式网络应用程序中发送推送通知。我已经创建了 curl 命令,当我在发送的终端推送通知中执行它时,如何在按钮单击时执行它?

这是我的 cURL 命令:-

curl --header "Authorization: key=AIzaSxUdg" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"cxA-dUj8BTs:APAvGlCYW\"]}"

这是我尝试过的:-

function send()
{
    navigator.serviceWorker.ready
    .then(function(registration) {
      registration.pushManager.getSubscription()
      .then(function (subscription) {        
        curlCommand(subscription);

    $.ajax({
        url: "https://android.googleapis.com/gcm/send",
        headers: {
            Authorization: "key=AIzaSxUdg",
        },
    contentType: "application/json",
    data: JSON.stringify({
        "registration_ids": [endpoint]
    }),         
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            type:"push",
            dataType: 'json'
})
.done(function() {
  alert('done');
})
.fail(function() {

     alert('err');// Error
});
})
})
}

但它显示错误 ----- XMLHttpRequest cannot load https://android.googleapis.com/gcm/send。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://localhost:8880 ”。

4

2 回答 2

3

Google API 旨在从服务器使用,因此它不包括 CORS 标头。

当您执行跨源 XHR(从您的域到 Google 的域)时,用户代理会发出一个预检请求以搜索告诉您的客户端有权执行操作的 CORS 标头。

为此,您需要向您的服务器发出请求(即 a POSTon /notifications/send),然后您的服务器应执行对 GCM 的 cURL 请求。

于 2016-04-19T11:39:11.547 回答
1

This will work:

function send()
{
    navigator.serviceWorker.ready
    .then(function(registration) {
      registration.pushManager.getSubscription()
      .then(function (subscription) {        
        curlCommand(subscription);

    $.ajax({
        url: "https://cors-anywhere.herokuapp.com/https://android.googleapis.com/gcm/send",
        headers: {
            Authorization: "key=AIzaSxUdg",
        },
    contentType: "application/json",
    data: JSON.stringify({
        "registration_ids": [endpoint]
    }),         
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            type:"push",
            dataType: 'json'
})
.done(function() {
  alert('done');
})
.fail(function() {

     alert('err');// Error
});
})
})
}
于 2019-08-01T12:46:10.370 回答