CROS (Cross-origin resource sharing) 跨来源资源共享的介绍
这个东西我想对写网页程式码的人来说,是个常会遇到的问题。而它出现的原因,主要是考虑浏览器在网路上传送资料安全性的关系,所以,下面我想把目前网路上对CROS (Cross-origin resource sharing) 跨来源资源共享提供的资料大概整理一下并做个介绍,如下:
跨来源资源共享(Cross-Origin Resource Sharing (CORS))
写网页程式码过程中,通常前台会用AJAX / API或 XMLHttpRequest的方式去跟Server 要资料,好,问题来了,就算成功传送出要求data的需求,但却会出现下列错误而要不到data,这是什么意思呢?如刚刚一开始所说的,主要是考虑浏览器在网路上传送资料安全性的关系,"同来源"的资源才可以相互存取,若是不同来源的资源,则必须符合在某些特定的情况下,才可以允许存取。
No 'Access-Control-Allow-Origin'header is present on the requested resource. Origin 'null' is therefore not allowed access.
那同来源和不同来源的定义怎么区别,下面简单举个例子来判断:
依这个网址为主, http://store.company.com/dir/page.html,若是遇到下列网址其代表是....
URL | 归类 | 备注 |
http://store.company.com/dir2/other.html | 同来源 | |
http://store.company.com/dir/inner/another.html | 同来源 | |
https://store.company.com/secure.html | 不同来源 | 协定不同 (http 与 https的差异) |
http://store.company.com:81/dir/etc.html | 不同来源 | 埠号不同 (http://store.company.com:81) |
http://news.company.com/dir/other.html | 不同来源 | 主机位置不同 (http://store.company.com 与http://news.company.com的差异) |
所以,从上面的举例而知,只要data是来自于不同网域(domain),通讯协定(protocol)或通讯埠(port),都被定义为不同来源,若要取得data,在浏览器这边送出一个 request 的时候,会在 request 的 header 塞入 Origin 这个资料,来让目前浏览网站的使用者代理取得存取其他来源(网域)伺服器特定资源权限的机制。
查看原文 >>