简体   繁体   中英

CORS error when fetching api from its own domain

One of app users constantly has an error when trying to fetch api from the same domain. This error occurs in Chrome only, other browsers are OK at his computer. He also tried to install Chrome CORS extention, but no luck. Does anybody has any idea why this might happen?

Error text below:

Failed to load http://my-app.com/api/v1/scoreboard : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://www.my-app.com ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If www and non www causing the problems of CORS. Then in my opinion you can set redirection of non WWW URL to WWW URL. It can be achieved using .htaccess or changing some settings on c-panel Here the related answer Redirect non-www to www in .htaccess

Another option is to set cors headers on server side.

Hope it helps

This depends on several things but usually calling code should not have any special configuration. instead your server side must decide to reject or allow the request. in case you can have a .htaccess file on your server side try to add this lines.

<IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
 Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT,PATCH"
 Header set Access-Control-Allow-Headers "Content-Type,Authorization"
</IfModule> 

Do not forget to add OPTIONS method in your allowed method list. Thats because the browser always checks the end-point availability by sending an OPTIONS request.

Adding 301 redirect from www to no-www domain name worked for me. Found solution here Nginx no-www to www and www to no-www

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM