6

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

aydow
  • 3,673
  • 2
  • 23
  • 40
Selvesan Malakar
  • 511
  • 2
  • 7
  • 20

2 Answers2

2

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.

Ravi Kumar
  • 993
  • 1
  • 12
  • 37
  • 1
    "thanks" this worked... I am using PHP as my backend code and used it's CURL to send request to the API by which i was successful to catch response **thankyou very much once again** – Selvesan Malakar Nov 14 '16 at 12:31
  • @SelvesanMalakar If this works for you, you might like to accept it as correct answer. It might help others to find correct answer for same/similar problem. – Ravi Kumar Nov 22 '16 at 10:13
  • Is calling API from Frontend and Backend different? – Fauzan Edris Dec 19 '22 at 09:20
1

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

aravithapa
  • 561
  • 6
  • 14