http://api.duckduckgo.com/?q=computer&format=json
(此服务器未启用CORS!)。
We can access the contents from this URL from any popular browser as a normal URL, browser has no issues opening this URL nor the server returns any error.
A server-side language like PHP/RoR can fetch the contents from this URL without adding any additional headers or special server settings. I used following PHP code and it simply worked.
$url='http://api.duckduckgo.com/?q=computer&format=json'; $json = file_get_contents($url); echo $json;
I just started working in javascript framework, AngularJS. I used following code...
delete $http.defaults.headers.common['X-Requested-With']; var url="http://api.duckduckgo.com/?q=computer&format=json"; $http.get(url) .success(function(data) { $scope.results=data; })
With above AngularJS code, I received following error:
XMLHttpRequest cannot load http://api.duckduckgo.com/?q=computer&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
AngularJS uses JQuery so I tried the same in JQuery with following code:
var url="http://api.duckduckgo.com/?q=computer&format=json"; $.getJSON(url , function( data ) { console.log(data); });
This also produced the same error as did AngularJS code.
Then my further research brought me to the point that it's actually not specific to JQuery and AngularJS. Both of these inherit this issue from Javascript!
- 这里有一个非常好的资源,解释了CORS是什么以及如何处理它:http://enable-cors.org/index.html。
- 此外,W3C也有官方的CORS规范:http://www.w3.org/TR/cors/
所以我的问题不是什么是CORS。我的问题是:
我理解的是,无论是Web浏览器还是PHP/RoR或JavaScript框架,都通过相同的HTTP或HTTPS请求URL,对吗?当然,是的。那么为什么当请求来自JavaScript时,HTTP必须更加安全呢?HTTP和服务器如何知道请求来自JavaScript?
当Web浏览器可以打开URL并且PHP/RoR(或任何服务器端语言)可以访问该URL而无需任何额外的设置/标头时,为什么AngularJS、JQuery(或一句话JavaScript)不能访问该URL,除非服务器为请求根设置了
Access-Control-Allow-Origin
标头?有哪些特殊功能(PHP/RoR具有的功能)在JavaScript中缺失,因此它无法在可以从其地址栏无问题打开该URL的同一浏览器中访问相同的URL?
只是想提一下,我基本上是一个iOS开发人员,最近开始学习Web开发,特别是AngularJS。所以我很好奇这一切是怎么回事,为什么会这样!