向 OneSignal 推送通知发送 POST 请求

Sending a POST request to OneSignal push notification

我有一个移动应用程序需要使用 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>

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

如今,Fetch API 优于 XHR。浏览器自带,还有轻量级的polyfills

const handleAsText = response => response.text();

const demo = document.getElementById("demo");

const displayResponse = responseText => demo.textContent = responseText;

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(displayResponse);
}