Cross-Origin Resource Sharing
Published by powerfulyang on Mar 27, 2022
Relate to https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
首先不谈 JSONP 这种注入执行动态js的方案。
Simple requests
A simple request is one that meets all the following conditions:
- One of the allowed methods:
- GET
- HEAD
- POST
- Apart from the headers automatically set by the user agent (for example,
Connection
,User-Agent
, or the other headers defined in the Fetch spec as a forbidden header name), the only headers which are allowed to be manually set are those which the Fetch spec defines as a CORS-safelisted request-header, which are:- Accept
- Accept-Language
- Content-Language
- Content-Type
- The only type/subtype combinations allowed for the media type specified in the
Content-Type
header are:application/x-www-form-urlencoded
multipart/form-data
text/plain
- If the request is made using an
XMLHttpRequest
object, no event listeners are registered on the object returned by theXMLHttpRequest.upload
property used in the request; that is, given anXMLHttpRequest
instancexhr
, no code has calledxhr.upload.addEventListener()
to add an event listener to monitor the upload. - No
ReadableStream
object is used in the request.
复杂请求
不符合简单请求的情况为复杂请求,请求流程如下:
1、PUT / DELETE 或者 Content-Type:application/json
类型的请求
2、发出 CORS 请求时,会在正式通信之前增加一次 “预检”请求(OPTIONS 方法),来询问服务器,本次请求的域名是否在许可名单中,以及使用哪些头信息
3、当 “预检”请求 通过以后,才会正式发起 请求,否则报错
头部信息概念
Access-Control-Allow-Origin
:*
设置可以访问的域名,* 表示所有网站都可以访问资源。Access-Control-Allow-Headers
:Origin,Last-Modified, Cache-Control
设置resquest headers
里哪些字段有效Access-Control-Allow-Methods
:POST、GET
允许请求的方式Access-Control-Allow-Credentials
:true
,允许携带Cookie
,同时 AJAX 请求中开启withCredentials
属性,xhr.withCredentials = true
,否则浏览器不会发送Cookie
document.domain
只能用于二级域名相同的情况下,比如 a.test.com
和 b.test.com
适用。
只需要给页面添加 document.domain = 'test.com'
表示二级域名都相同就可以实现跨域