Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest blocked by CORS Policy

I add an API with following script in let's say http://www.test.com:

<script src="http://apiendpoint.com/api/v1/api.js"></script>  <div id="api" data-apikey="LA59CJI9HZ-KIJK4I5-3CKJC"></div> 

api.js

$(function () {    apikey = $('#api').data('apikey');   $("#api").load("http://apiendpoint.com?apikey=" + apikey);  }) 

When I load the page, I get following error:

XMLHttpRequest cannot load apiendpoint URL. Redirect from 'apiendpoint URL' to 'apiendpoint URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'test URL' is therefore not allowed access.

In the path of apiendpoint.com I added in .htaccess following code:

Header set Access-Control-Allow-Origin "*" 

But it does not work.

like image 925
Prolativ Avatar asked Sep 18 '17 10:09

Prolativ


People also ask

How do I unblock my CORS policy?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.

How do I resolve access to XMLHttpRequest?

In simple words, this error occurs when we try to access a domain/resource from another domain. To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.

How do you resolve a CORS policy issue?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.


2 Answers

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

like image 197
foakesm Avatar answered Sep 21 '22 02:09

foakesm


I know this might be late, but hope this will help others. This problem comes from backend side, call CORS. I'm using java for backend so I added@CrossOrigin to Controller class. It works!

like image 31
Đào Anh Thành Avatar answered Sep 21 '22 02:09

Đào Anh Thành