url不完整时,XMLHttpRequest访问控制允许源 [英] XMLHttpRequest Access Control Allow Origin when url is not complete

查看:38
本文介绍了url不完整时,XMLHttpRequest访问控制允许源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我提交ajax请求时会出现此错误

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?

推荐答案

同一出处政策表示您无法分析来自另一个来源"(域,端口)的数据(json,html,图像等).

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

请注意

术语来源"是使用域名,应用程序层定义的 协议,以及(在大多数浏览器中)HTML文档的端口号 运行脚本

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

一种解决方案是在提供其他数据的服务器上设置 CORS标头明确允许访问:

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.

一种间接的解决方案是,通过在服务器上放置代理,使浏览器认为只有一个来源.在apache上,您不需要.htaccess,而需要mod_proxy.如果您想安装这样的代理,您可能会对此SO问题(实际上,您可能会对答案有所帮助,因为答案帮助我在我的一台服务器上设置了这样的代理.

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).

如果唯一的问题是人们键入mysite.com而不是www.mysite.com,并且您只有一台服务器,则可以简单地使用.htaccess重写URL:

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]

这篇关于url不完整时,XMLHttpRequest访问控制允许源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆