The 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin

喜你入骨 提交于 2020-12-29 12:21:30

问题


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!


回答1:


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/




回答2:


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




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/38043194/the-access-control-allow-origin-header-has-a-value-that-is-not-equal-to-the-su

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!