XMLHttpRequest Access Control Allow Origin when ur

2019-09-07 03:19发布

Sometimes when I submit ajax requests I get this error

XMLHttpRequest cannot load http://www.mysite.com/go/submit. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.

Here are solutions I thought about:

* Add the allow origin rule everywhere?
* Write .htaccess to always redirect to full url
* Use this method http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

How should I fix this problem?

标签: php ajax http
1条回答
对你真心纯属浪费
2楼-- · 2019-09-07 04:06

The same origin policy means you cannot analyze data (json, html, image, etc.) that are coming from another "origin" (domain, port) than yours.

Note that

The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script

A solution is to set, on the server serving the other data, CORS headers explicitly allowing the access :

Access-Control-Allow-Origin: *

So you must have control of the server serving the data you embed as soon as you're not just displaying them.

A somewhat indirect solution is to let the browser think there is only one origin, by putting on your server a proxy. On apache you don't need .htaccess but mod_proxy. If you want to install such a proxy, you may be interested by this SO question (in fact you'd probably be more interested by the answer which helped me set such a proxy on one of my servers).

If your only problem is people typing mysite.com instead of www.mysite.com and you have only one server, you may simply use .htaccess to rewrite the URL :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [L,R=301]
查看更多
登录 后发表回答