Getting Cross Origin Error While Calling API From Jquery AJAX

Reema picture Reema · Nov 26, 2018 · Viewed 11.8k times · Source

I Got Following Error While Calling API From AJAX Jquery.

Access to XMLHttpRequest at 'https://www.demo.in/rest/employee/mapping/v3/9714620362' from origin 'http://localhost:8191' 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

I don't have Access To Change API Coding. I just have API call From javascript or Jquery. I used Following Code For Calling REST API.But I is not Working.

$.ajax({
        url: 'https://www.demo.in/rest/employee/mapping/v3/9714620362',
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type':'application/json'
        },
        method: 'GET',
        dataType: 'json',
        data: '',
        success: function(data){
          console.log('succes: '+data);
        }
      });

Answer

Alok picture Alok · Nov 26, 2018

Update the dataType to "jsonp" and it should work

$.ajax({ url: 'https://www.demo.in/rest/employee/mapping/v3/9714620362', headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type':'application/json' }, method: 'GET', dataType: 'jsonp', data: '', success: function(data){ console.log('succes: '+data); } });