Search code examples
javascriptjqueryhttp-post

Post Request works in swagger but not in JavaScript or jQuery


So, I am trying to call a rest API using ajax post. Response contains Status code and Response body which in JSON. When I test this in swagger it works.

enter image description here

When I try this in either JavaScript or JQuery,

const values = {
    clientId: '9d9d865a-96c6-41ff-9842-89101c8ccc7a'
};

$.ajax({
    url: "https://-----.-----------.ca/Asset/EstimatedWaitTime",
    type: "POST",
    data: values,
    contentType: "application/json",
    dataType: "text",
    beforeSend: function(xhr) {
        xhr.setRequestHeader('access-control-allow-headers', 'Origin, X-Requested-With, Content-Type, Accept');
    success: function(response) {},
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
    }
});

I get the following error:

enter image description here

Why is this not working, or what am I doing wrong?

Thank you guys!


Solution

  • It's a Cross-Origin Resource Sharing (CORS) error https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS Best way is your own API with access to external web resource. JS (AJAX request) -> Your API -> External web resource -> Your API -> Your Web page (js response)