Sending JSON Data with Javascript Post Request

I've been attempting to send a JSON payload via a JavaScript script, but my webhooks don't seem to recognize the payload no matter what I try.

Here is the code that I compiled from various online resources:

let xhr = new XMLHttpRequest();

xhr.open("POST","https://webhook.site/4530328b-fc68-404a-9427-3f2ccd853066/",true);

xhr.setRequestHeader("Content-Type", "application/json");

let data = JSON.stringify({'eventType' : 'test'});

xhr.send(data);

Although I'm not well-versed in JavaScript development, it appears to me that this code should work. However, whenever I run this snippet, the POST URL doesn't provide any response back :/

Any thoughts on why this might be happening? :)

Thank you for your attention!

Answer №1

It seems that the webhook.site service you are trying to connect to using your JavaScript code does not have the necessary CORS headers enabled by default. These headers are essential for ensuring proper security measures on modern browsers. If you check the developer console in your browser, you may see an error message similar to this:

Access to XMLHttpRequest at 'https://webhook.site/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This error indicates that the requested resource does not include a valid Access-Control-Allow-Origin header, which prevents the POST request from completing successfully. To resolve this issue, you can enable the CORS Headers option in the webhook.site user interface. This will ensure that the proper CORS headers are sent, allowing your code to work correctly.

let xhr = new XMLHttpRequest();

xhr.open("POST","https://webhook.site/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa",true);

xhr.setRequestHeader("Content-Type", "application/json");

let data = JSON.stringify({'eventType' : 'test'});

xhr.send(data);

Answer №2

If you want to make a post request, I recommend using axios. Here is an example of how to do it:

const result = await axios.post('https://webhook.site/4530328b-fc68-404a-9427-3f2ccd853066/', {'eventType' : 'test'});

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

JavaScript Cookie Array Handling

Is it possible to create a 2D array as a cookie in JavaScript? If so, how can I go about creating this array cookie and looping through it to retrieve data efficiently? Any guidance on this would be greatly appreciated. Thank you! ...

What is the reason that accessing array elements with negative indices is significantly slower compared to accessing elements with

Let's explore a JavaScript performance test: const iterations = new Array(10 ** 7); var x = 0; var i = iterations.length + 1; console.time('negative'); while (--i) { x += iterations[-i]; } console.timeEnd('negative'); var y = ...

The JSP AJAX response comes back empty

I am encountering an issue where I am using JQuery Ajax to call a REST API in JSP, but it keeps returning null no matter how I try. Strangely enough, the same code works when used in HTML. I have been searching online for a solution but haven't found ...

How to efficiently switch between classes in Ember Octane using Handlebars?

What is the best way to toggle between displaying a class on and off using Ember.js Octane? Should I use an @action or @tracked in this case? <img src="flower.jpg" alt="flower" class="display-on"> or <img src="flower.jpg" alt="flower" class=" ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

What is the best way to retrieve an object from the state in my React application?

I have been struggling to locate an item from a collection so that I can update my react component. Despite the fact that the propertyState object is not empty and contains a list that I have successfully console logged, I keep receiving an undefined obj ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Postman result when using json_encode() function

After retrieving a simple JSON from my PHP file, it displays correctly on the page. However, when attempting to access the link in Postman, an HTML error occurs. The PHP encoding function is as follows: <?php require 'connection.php'; showSt ...

Tips on integrating JavaScript with embedded Ruby code

I am attempting to generate a flash message that displays after a user clicks a link in my js.erb file. $('a').click(function(){ <% flash.now[:alert]= "Successfully added "%> this.innerHTML <% "to cart" %> }) M ...

Trouble with AJAX communicating with PHP and not rendering fresh data

I have created a row of images that are clickable, and once clicked, a variable is sent via AJAX to a PHP file for a database query. The PHP file receives the variable and executes the correct query. However, instead of updating the HTML on my page, it sim ...

Transforming a composite type into an empty structure with to-json in Postgres

Showing an illustration with PostgreSQL (9.4) where a local variable of a composite type is transformed into a JSON string, it becomes apparent that PostgreSQL treats differently a variable with null value compared to a null-value cast to the same type. I ...

Jquery adds a fun, wobbly effect to animations

I'm experiencing an issue with the animation I've implemented causing some slight shaking and wobbling of the text and certain elements which is affecting the overall look. You can view a live example of this behavior here: This problem specific ...

Encountered an issue when trying to convert JSON into an array and loop through it in an HTML file using a

Currently, I am working on a project involving Angular where I am retrieving data from an API through a GET call. Specifically, one column's data is being converted from JSON to an array. However, when attempting to iterate over this array in the HTML ...

In swift 3.0, the tableview is unable to display data obtained from a web API in JSON format

Recently, I delved into IOS development using swift 3.0 and created a basic app to fetch data from a server database via a web API. The JSON data was successfully retrieved and parsed into a string array. However, despite being able to print the array, I f ...

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...

A guide to displaying a DIV element upon clicking a button in ReactJs

While developing a form, I encountered the need to render the same div in the "Active Membership" section whenever the "Add More" button is pressed. Since users can have multiple active memberships, each time the button is clicked, the input section shou ...

Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download? JSX Section axios .get( "/excel/export/dashboardTable", {} ) .then(resp => { //success call ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

"Drag and drop elements that automatically snap to a grid and move with

I'm trying to create a small, square div that follows the mouse cursor, but I want it to snap to a 3x3 pixel grid. Here is what I have so far: $(document).mousemove(function(e) { window.x = e.pageX; window.y = e.pageY; if(window.x % 9 === 0 ){ ...

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...