Selvesan Malakar
Selvesan Malakar

Reputation: 571

CORS error when jquery ajax request on api

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!!!

Upvotes: 6

Views: 12615

Answers (2)

aravithapa
aravithapa

Reputation: 631

The cors error is cross origin request policy maintained by the browser for security. To solve your problem either you will have to allow cors request in your server coding or if you do not have access to the server api code you will have to make the api call from your server to api server

Upvotes: 1

Ravi Kumar
Ravi Kumar

Reputation: 993

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.

Upvotes: 2

Related Questions