将POST请求发送到OneSignal推送通知

时间:2018-09-22 02:45:39

标签: javascript json post onesignal

我有一个移动应用程序,需要使用OneSignal API通过POST接收通知。我在Postman上进行了测试,一切都很好。现在我要做的是:抓取一个JavaScript代码段并使用OneSignal API来向我的手机发送任何推送通知。 现在,我正在尝试使用w3Schools上的示例执行此操作,但是它似乎不起作用。 这就是我试图做到的方式:

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "https://onesignal.com/api/v1/notification", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  xhttp.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxxxxx");
  xhttp.send({
        "app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
        "contents": {"en": "Hello World!"} ,
        "included_segments" : ["All"]
});
}
</script>

</body>
</html>

我真的不明白我应该怎么做。

1 个答案:

答案 0 :(得分:1)

如今,Fetch API比XHR更受青睐。它与浏览器一起提供,并且有轻量级的polyfills。

const handleAsText = response => response.text()

const demo = document.getElementById("demo")

function loadDoc() {

  const method = "POST"
  const headers = {
    "Content-type": "application/json";
    "Authorization": "Basic xxxxxxxxxxxxxxxxxx";
  }

  const body = JSON.stringify({
    "app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "contents": {"en": "Hello World!"} ,
    "included_segments" : ["All"]
  }) 

  return fetch("https://onesignal.com/api/v1/notification", {method, headers, body})
    .then(handleAsText)
    .then(responseText => demo.textContent = responseText);
}