微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

跨域 – AngularJS对跨源资源执行OPTIONS HTTP请求

我试图设置AngularJS与跨源资源通信,其中提供我的模板文件的资产主机是在不同的域,因此XHR请求角执行必须是跨域。我已经添加了适当的CORS头到我的服务器的HTTP请求使这项工作,但它似乎不工作。问题是,当我在我的浏览器(chrome)中检查HTTP请求时,发送到资产文件的请求是一个OPTIONS请求(它应该是一个GET请求)。

我不知道这是否是AngularJS中的错误,或者如果我需要配置的东西。从我的理解,XHR包装器不能做一个OPTIONS HTTP请求,所以它看起来像浏览器试图找出是否“允许”下载资源首先执行GET请求。如果是这样,那么我需要为资产主机设置CORS头(Access-Control-Allow-Origin:http://asset.host …)吗?

OPTIONS请求不是一个AngularJS错误,这是跨源资源共享标准强制浏览器的行为。请参考本文档: https://developer.mozilla.org/en-US/docs/HTTP_access_control,其中在“概述”部分中说:

The Cross-Origin Resource Sharing standard works by adding new HTTP
headers that allow servers to describe the set of origins that are
permitted to read that information using a web browser. Additionally,
for HTTP request methods that can cause side-effects on user data (in
particular; for HTTP methods other than GET,or for POST usage with
certain MIME types). The specification mandates that browsers
“preflight” the request,soliciting supported methods from the server
with an HTTP OPTIONS request header,and then,upon “approval” from
the server,sending the actual request with the actual HTTP request
method. Servers can also notify clients whether “credentials”
(including Cookies and HTTP Authentication data) should be sent with
requests.

很难提供一个适用于所有WWW服务器的通用解决方案,因为设置将根据您打算支持的服务器本身和HTTP动词而有所不同。我建议您阅读这篇有关需要由服务器发送的确切标题的更多详细信息的优秀文章(http://www.html5rocks.com/en/tutorials/cors/)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐