提取在Web通知推送

时间:2019-01-18 11:46:08

标签: php jquery web notifications fetch

我目前正在研究网络通知,但偶然发现了this guide。当前一切都很好,但是fetch()中似乎有一个错误,因为它返回了未定义的响应错误。

function sendSubscriptionToBackEnd(subscription) {
  return fetch('send_notification.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(subscription)
  }).then(function(response) {
    console.log(response);
    if (!response.ok) {
      throw new Error('Bad Status code from server');
    }
    return response.json();
  }).then(function(responseData) {
    if (!(responseData.data && responseData.data.success)) {
      throw new Error('Bad response from server.');
    }
  });
}

send_notification.php

<?php
  echo json_encode(array("response"=>"ok"));
?>

通过时的外观如下:

send_notification

enter image description here

我不知道为什么我的send_notification没有得到回应。这是我的整个文件:https://www.mediafire.com/file/nbxe6ks3sjntjj0/push_notification2.zip/file

---------编辑----------- 这就是我对未定义响应的意思。

enter image description here

2 个答案:

答案 0 :(得分:1)

response对象没有ok属性。 okresponse属性的 string值,因此您的逻辑应为:

if (response.response != 'ok') {
  // your logic...
}

您将与response.json()遇到相同的问题,但是对于您期望的结果,我无法做出合理的猜测。

>

答案 1 :(得分:0)

我尝试了您的代码,它可以正常工作。 console.log(response)返回200 OK。

相关问题