JavaScript jQuery – Fixing CORS Error During AJAX Request on API

ajaxapijavascriptjqueryjson

I am using jQuery ajax to send request to some API. Due to the CORS policy I got a CORS error on the browser's console

Here's by code

$.ajax({
        url: sendHere,//api url
        type: 'GET',
        contentType: 'text/plain',
        crossDomain: true,
        beforeSend: function(xhr){
            xhr.withCredentials = true;
        },
    }).done(function (result) {

        console.log(result);

    }).error(function (err) {
        //console.log(err);
    });

Error

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mywebsite.com' is therefore not allowed access.

I tried to solve this problem by installing a chrome extension to enable allow cross origin request. This extension somehow solved my problem and got a response from the api. But installing an extension is not good.

I also tried to make the request with JSONP(dataType:'jsonp') but the response given by the api is not in json format, it is string so it gives an error.

Code with JSONP

$.ajax({
        url: sendHere,//api url
        type: 'GET',
        crossDomain: true,
        dataType:'jsonp',
    }).done(function (result) {

        console.log(result);

    }).error(function (err) {
        //console.log(err);
    });

Uncaught ReferenceError: E0002 is not defined
where "E0002" is the response string from the api

!!!PLEASE HELP!!!

Best Answer

There are 2 situations -

  1. If you have control over the api code then

    make changes in header and add your origin as well.

  2. If you don't have control to change CORS header that is coming from the api

    you have only one option create a backend code(your own api) in any language you prefer that make an http request and get the data. now use your own api to get data on your frontend.

Related Question