6

I am trying to login with ajax to an API and I get this error:

XMLHttpRequest cannot load. The 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin. Origin 'http://localhost' is therefore not allowed access.

I read all about this error, all over the internet, and I've tried all the solutions I could find online. I modified the .htaccess and apache httpd configuration file according to the CORS instructions here: http://enable-cors.org/server_apache.html

Access-Control-Allow-Origin: *

Nothing seems to be working. I'd really appreciate if you guys can help me out with this. Thank you!

Daniel R.
  • 361
  • 1
  • 4
  • 16

4 Answers4

3

You have to set Access-Control-Allow-Origin header to * or specified value http://localhost

You can do this through:

1- Your code

2- .htaccess file

3- Server config (restart web server required)

Here is the link that show how to do it on apache

http://access-control-allow-origin-guide.com/enable-cors-on-apache-linux/

Dzung Cao
  • 49
  • 3
0

i use htaccess file for load JSON data in different hosting, and its works but

it have to put inside the public html root of our web hosting for example

uploading .htaccess into --> (https://freehostingsomewhere.com/)

then inside .htaccess

<FilesMatch "\.(ttf|otf|eot|woff|jpg|png|jpeg|gif|js|json|html|css)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://localhost"
  </IfModule>
</FilesMatch>

in here i use http://localhost to development and it works,

maybe if i have another web host just change it into that url, i will try it later (it can, i already try it) :p

this is just for more clear explanation

cheers :p

0

As added browser security, unless the API allows cross-browser origins in the the return responses header there is no way around this.

The browsers are blocking it, there is a plugin to allow for chrome but it is not realistic to depend on browser plugin to allow end user requests,

Try and reach out to the API provider and see if they can look into updating the header in the response.

It is a CORS issue: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

jeremykenedy
  • 3,634
  • 1
  • 14
  • 23
0

Are your requests using either cookies or authorization by any chance?

Check on your ajax call on the client side if you're configuring it to be done "with credentials"

.withCredentials = true;

If yes, the wildcard(*) will not work and you'll need to provide the exact host as the value for Access-Control-Allow-Origin.

Refer to this stack overflow answer or Mozilla Documentation on CORS

Community
  • 1
  • 1
fmello
  • 553
  • 2
  • 9