0

400尝试使用 StreamElements API 向 twitches IRC 聊天发送消息时出现错误。

到目前为止,这是我的代码,我知道它不正确,但我不知道如何将消息传递给 twitch 以便它接受它。我正在学习 ajax 并将在未来学习 jQuery,但是如果可以请在 vanilla JS 中提供帮助。

var data = {"message": "test"};
var token = "secret"
var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open("POST", "https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("Authorization", `Bearer ${token}`);

xhr.send(data);
4

1 回答 1

1

XMLHttpRequest is a bit old library to make HTTP request.

Consider using the new fetch API in (vanilla) JavaScript.

var data = { message: "test"};
var token = "secret"

await fetch('https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify(data)
})
.then(response => response.json()) 
.then(result => { 
   console.log(result)
})
.catch(err => {
   console.log(err)
})
于 2020-05-24T07:32:47.263 回答