0

I am getting a 400 error when trying to send a message to twitches IRC chat with StreamElements API.

Here is my code so far I know it is incorrect but I don't know how to pass the message to twitch in order for it to accept it. I am learning ajax and will be learning jQuery in the future however if the help could please be in 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);
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Paul Hashmi
  • 456
  • 5
  • 18

1 Answers1

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)
})
Vimal Munjani
  • 280
  • 1
  • 8
  • Also I see, in your XHR request, you are not stringifying your object to be sent as JSON string. use `xhr.send(JSON.stringify(data));` – Vimal Munjani May 24 '20 at 07:34