type
status
date
slug
summary
tags
category
icon
password
AI summary
Last edited time
Mar 7, 2024 04:34 AM
浏览器同源策略
浏览器安全的基石是”同源策略”(same-origin policy). "同源"指的是"三个相同":
- 协议相同
- 域名相同
- 端口相同
如果非同源,共有三种行为受到限制。
Cookie
、LocalStorage
、IndexDB
无法读取
DOM
无法获得
AJAX
请求不能发送
CORS原理解析
CORS
是跨源AJAX
请求的根本解决方法. JSONP
只能发GET
请求, 但是CORS
允许任何类型的请求.整个
CORS
通信过程都是浏览器自动完成的, 不需要用户参与. 对于开发者来说, CORS
通信与同源的AJAX
通信没有差别, 代码完全一样. 浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多一次附加的请求,但用户不会有感觉。因此,实现CORS
通信的关键是服务器. 只要服务器支持 CORS, 就可以跨源通信.简单请求和非简单请求
直接在请求时加上
Origin
的 header 
发出请求前, 会发起一次
OPTION
请求
Nginx CORS 配置
add_header
不是所有返回都会追加,只限特定状态码的返回才有效,如果想所有返回都生效需要加上always
选项参数官方的解释
CORS 响应头说明
header | 是否必填 | 说明 |
Access-Control-Allow-Origin | Y | Access-Control-Allow-Origin 它的值要么是请求时Origin 字段的值,要么是一个* ,表示接受任意域名的请求, 不推荐* |
Access-Control-Allow-Credentials | N | The Access-Control-Allow-Credentials header indicates whether or not the response to the request can be exposed when the credentials flag is true. |
Access-Control-Expose-Headers | N | The Access-Control-Expose-Headers header adds the specified headers to the allowlist that JavaScript (such as Response.headers ) in browsers is allowed to access. |
Access-Control-Allow-Headers | Y | The Access-Control-Allow-Methods header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. |
Access-Control-Allow-Methods | Y | The Access-Control-Allow-Methods header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. |
Access-Control-Max-Age | N | The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached. |
CORS 请求头说明
header | 说明 |
Origin | The Origin header indicates the origin of the cross-origin access request or preflight request. |
The Access-Control-Request-Method is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made. | |
The Access-Control-Request-Headers header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made (for example, by passing them as the headers option to the Request() constructor). This browser-side header will be answered by the complementary server-side header of Access-Control-Allow-Headers . |