【问题标题】:fetch returns undefined error in Web notification Pushfetch 在 Web 通知推送中返回未定义的错误
【发布时间】:2019-06-12 16:22:54
【问题描述】:

我目前正在研究网络通知,我偶然发现了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 没有回复。这是我的整个文件:https://www.mediafire.com/file/nbxe6ks3sjntjj0/push_notification2.zip/file

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

【问题讨论】:

    标签: php jquery web notifications fetch


    【解决方案1】:

    response 对象没有 ok 属性。 okresponse 属性的字符串值,因此你的逻辑应该是:

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

    response.json() 会出现同样的问题,但是我无法做出符合逻辑的猜测,因为您期望在显示的图像中给出输出。

    【讨论】:

    • 嗨,我更新了我的问题。正如你所看到的,我认为这不是问题所在。我只是认为“响应”就像我的 send_notification 的返回值,但无论如何,如图所示,我的 fetch 之后的“响应”似乎有错误。 @罗伊
    【解决方案2】:

    我试过你的代码,它运行没有任何问题。 console.log(response) 返回 200 OK。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-07
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多