适用对象

首先,CORS策略只针对脚本(script),即通过script加载的资源才受到限制。

通过HTTP Tag加载Images、CSS文件不受限制(例外,字体文件受限制)。

It is very important to remember that the same-origin policy applies only to scripts. This means that resources such as images, CSS, and dynamically-loaded scripts can be accessed across origins via the corresponding HTML tags[2] (with fonts being a notable exception[3]). Attacks take advantage of the fact that the same origin policy does not apply to HTML tags.

举例

<http://x.a.local/cors.html>
<html>
	<head>
     <!-- 不受限制-->
		<link href="<http://b.local/direct.css>" rel="stylesheet" type="text/css">
		<style type="text/css">
		@font-face {
			font-family: 'FontAwesome';
			src: url('<http://b.local/x.eot?v=4.2.0>');#字体受到限制
			font-weight: normal;
			font-style: normal
		}
		body {
			font-family: 'FontAwesome', Fallback, sans-serif;
		}
		</style>
	</head>

	<body>
		<h1>What a wonder world</h1>
	</body>
</html>

多级情况

A站通过link加载B站CSS,B站CSS内加载了字体,出现跨域问题

<http://x.a.local/cors.html>
<html>
	<head>
     <!-- 不受限制-->
		<link href="<http://b.local/direct.css>" rel="stylesheet" type="text/css">
		</style>
	</head>

	<body>
		<h1>What a wonder world</h1>
	</body>
</html>

<http://b.local/direct.css>
@font-face {
	font-family: 'FontAwesome';
	src: url('/x.eot?v=4.2.0');
	font-weight: normal;
	font-style: normal
}
body {
	font-family: 'FontAwesome', Fallback, sans-serif;
}

Untitled

当出现跨域,解决办法(怎么规定怎么来)

简单情况,加Access-Control-Allow-Origin

复杂情况,多一个OPTIONS请求

What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request.

带COOKIE的情况

client js需要显示指定携带cookie

XMLHttpRequest 或 Fetch 与 CORS 的一个有趣的特性是,可以基于 HTTP cookies 和 HTTP 认证信息发送身份凭证。一般而言,对于跨源 XMLHttpRequest 或 Fetch 请求,浏览器不会发送身份凭证信息。如果要发送凭证信息,需要设置 XMLHttpRequest 的某个特殊标志位

var invocation = new XMLHttpRequest();
var url = '<http://bar.other/resources/credentialed-content/>';

function callOtherDomain(){
  if(invocation) {
    invocation.open('GET', url, true);
    invocation.withCredentials = true;
    invocation.onreadystatechange = handler;
    invocation.send();
  }
}