Encountered a problem trying to post a message to Twitch chat using JavaScript and StreamElements

I'm encountering a 400 error when attempting to send a message to Twitch's IRC chat using the StreamElements API.

This is my current code, and I am aware that it is incorrect. I'm struggling with passing the message to Twitch in order for it to be accepted. I am currently learning AJAX and plan to learn jQuery in the future, but I would appreciate assistance using vanilla JavaScript.


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

Answer №1

XMLHttpRequest may be considered outdated when it comes to making HTTP requests.

You might want to explore the newer fetch API available in plain 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)
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Email notification sent by Nodemailer indicates that the message is currently in a

I'm currently integrating Nodemailer into my React/Express project, and I've encountered an issue where the server indicates that it's posting data but in the network tab, it remains pending indefinitely. Here is the snippet of my code: cons ...

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

"Utilizing JavaScript to Disable a MenuItem in ASP .NET: A Step-by-Step

I have successfully designed a customized menu interface using ASP.NET. <asp:Menu ID="Name1" runat="server" OnMenuItemClick="DoSth_MenuItemClick" Visible="true"> <Items> <asp:MenuItem Text="Function description" Value="Val" ToolTip=" ...

Step-by-step guide on adding a gallery image in Node.js

I need help with posting my gallery image to a nodeJs server. Here is the code I am currently using: vm.getImageSaveContactInst = function() { var options = { maximumImagesCount: 1, // Only selecting one image for this example width ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

Changing the appearance of a website by applying various stylesheets based on the size of the browser window in

After implementing the code below to switch between stylesheets based on browser height, I encountered a small issue. The code works perfectly when the page first loads or when the window is resized and then refreshed. However, I'm curious if there&ap ...

What could be the reason my JavaScript alert is not functioning properly?

Having some trouble with my form validation using Bootstrap - the alerts aren't showing up when I submit the form. Not all of the alerts have been added yet. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

php receiving no value in ajax response

In an attempt to create search suggestions similar to Google, I have set up a table with tags and a single column called 'tag' to store the tags. However, I am encountering an issue where if I input nothing or a tag that is already in the databas ...

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

After placing two divs within another div and applying justify content, an unexpected blank space has appeared

I am currently working on a website project using the Next.js framework for React and Tailwind CSS for styling. However, I have come across an issue that is causing some trouble. My goal is to position an image on the right side of the page while keeping t ...

Error handling with JSON in Parse.com causes compatibility issues in Express js 4

I need help figuring out why the data I send in a POST call to an Express JS server hosted on Parse.com is not being received properly. This is how I send the data: var data = new Array(); data["firstName"] = firstName; data["lastName"] = las ...

What could be causing my right-floating elements to shift more towards the left with each occurrence?

After following a todo list tutorial, everything was running smoothly until I decided to add some styling to it. I placed a Font Awesome trash can icon inside a button with the class "remove." Essentially, I removed all the styles from the button, leaving ...

Communication between Laravel and controller using AJAX for exchanging information

I have a specific AJAX function being called from a view: function gatherProductData() { var productIds = []; $('#compare-widget tbody tr').each(function(i, ele) { productIds[i] = $(ele).data('product-id'); }); ...

Position of Vertices in Three.js PolyhedronGeometry

Currently, I am experimenting with creating my own unique shape using PolyhedronGeometry In a rough sketch: https://i.sstatic.net/PREZN.jpg I've encountered some challenges. Specifically, I'm attempting to attach this newly created shape onto a ...

Is there a way to remove a link to an image that pulls data from another website?

On my HTML page, I have implemented the following code to display weather data: <!-- Begin Weather Data Code --> <div style="display:none;"> <a href="http://iushop.ir"> <h1>Weather</h1> </a> </div> < ...

What is the best approach for handling @RequestParam in a JSP file?

Hello there! I have a query regarding the usage of @RequestParam in @RestController. My question is about extracting @RequestParam from the client side. Below is an example of server code using @RestController: @ResponseBody @RequestMapping(method = Reque ...

Randomly injecting strings like 'jQuery111201xxx' into a string using jQuery Ajax

After implementing a booking system that utilizes FullCalendar, I encountered an unusual issue with the 'notes' field. Occasionally, a strange string is inserted into the notes field at random points. Here's an example of what I found recent ...

Challenges Arising from Using Django ORM with AJAX

Hey there! I need some help with Django ORM and ajax requests related to the select_related function. Let me explain what I'm trying to do. I have a query like this: prod_serv = Product_service.objects.select_related() This query involves joining 3 ...

What is the reason for Bower consistently choosing to download the Angular version 1.5.9-build.5086+sha...?

Struggling to manage my front end dependencies using bower.json. No matter how I specify the version of Angular in bower, a different version is downloaded every time. The issue is that many functionalities in my code rely on previous versions of Angular, ...