Paul Hashmi
Paul Hashmi

Reputation: 466

Error while sending a message to twitch chat with Javascript StreamElements

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

Upvotes: 0

Views: 1159

Answers (1)

Vimal Munjani
Vimal Munjani

Reputation: 290

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

Upvotes: 1

Related Questions