You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
简单地说,same-origin policy表示浏览器应该只允许在HTML页面的第same domain页对服务进行ajax调用.
示例:
http://www.example.com/myPage.html
的页面只能直接请求http://www.example.com
的服务,比如http://www.example.com/api/myService
.如果服务托管在另一个域(比如http://www.ok.com/api/myService
),浏览器将不会直接拨打电话(如您所料).相反,它将try 提出CORS请求.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
- Will include an
Origin
header in the original request (with the page's domain as value) and perform it as usual; and then
- Only if the server response to that request contains the adequate headers (
Access-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
- If the expected headers don't come, the browser simply gives up (like it did to you).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
How to fix it?
Was it just a typo?有时候JavaScript代码在目标域中只是一个输入错误.你查过了吗?如果页面为www.example.com
,则只会定期拨打www.example.com
!其他URL,例如api.example.com
,甚至example.com
或www.example.com:8080
,被浏览器视为different个域!是的,如果端口不同,那么它是一个不同的域!
Add the headers.到enable CORS的最简单方法是向服务器的响应添加必要的报头(如Access-Control-Allow-Origin
).(每种服务器/语言都有实现这一点的方法-check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.