I've been trying to send a JSON payload through a JS script but my webhooks seem unable to see the payload whatever I write.
Here is the code I put together from various online sources:
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);
I'm not a JS developer but it seems to me that this should work. However every time I run this snippet the POST URL does not show anything back :/
Any idea why that is over here :) ?
Thank you for your time!
CodePudding user response:
In your example, the webhook.site
service you're attempting to connect to with your JavaScript isn't enabled (by default) with the proper CORS headers that modern browsers respect & enforce to improve user security. The developer console in your browser of choice should point this out to you; the error mine gave back was:
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.
As the error states, the requested resource doesn't respond with any valid Access-Control-Allow-Origin
header, which will prevent the POST
itself from being fully executed. In webhook.site
, you can select the CORS Headers
tickbox from the top of the user interface to enable the service to send the proper CORS headers to get this working.
let xhr = new XMLHttpRequest();
xhr.open("POST","https://webhook.site/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa",true); // configuration interface at https://webhook.site/#!/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa/e14fc471-4bc4-410f-b16a-0755a231fb12/1
xhr.setRequestHeader("Content-Type", "application/json");
let data = JSON.stringify({'eventType' : 'test'});
xhr.send(data);
CodePudding user response:
I suggest you to use axios, it gonna be something like this and you will get the response from your post request
const response = await axios.post('https://webhook.site/4530328b-fc68-404a-9427-3f2ccd853066/', {'eventType' : 'test'});