首页 文章

向OneSignal推送通知发送POST请求

提问于
浏览
1

我有一个移动应用程序,需要使用OneSignal API通过POST接收通知 . 我在Postman上测试它,一切都很顺利 . 现在我想要做的是: grab 一个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 回答

  • 1

    如今,Fetch API优于XHR . 它配有浏览器,并有轻量级的polyfill .

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

相关问题