56

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.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Prolativ
  • 727
  • 1
  • 7
  • 12
  • 1
    Check using your browser tools network tab to verify that the header is present – Ferrybig Sep 18 '17 at 10:42
  • Also Clear your browser cache. – Ataur Rahman Munna Sep 18 '17 at 10:44
  • Download CORS plugin from chrome store and try making a request after turning it on. – codeslayer1 Sep 18 '17 at 10:44
  • @Ferrybig The response header don't contain "Access-Control-Allow-Origin:*". But when i load the URL directly it contains the Access-Control-Allow-Origin:* – Prolativ Sep 18 '17 at 12:20
  • @codeslayer1 I already downloaded the plugin and it works, but this is not the solution – Prolativ Sep 18 '17 at 12:21
  • Check the request type, the first request is an Options request, this one should also contain the header (and you may need to allow options requests in apache) – Ferrybig Sep 18 '17 at 12:23
  • 1
    I believe [sideshowbarker 's answer here](https://stackoverflow.com/a/43881141/7886100) will have all the info you need to fix this – foakesm Oct 11 '18 at 10:01
  • Possible duplicate of [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – Boiethios May 03 '19 at 13:20

2 Answers2

12

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

foakesm
  • 803
  • 10
  • 18
4

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!