前言
跨域资源限制是浏览器限制的,后端直接访问没有经过浏览器是可以访问的。
简单请求和非简单请求(预检请求)
-
简单的请求是不会触发CORS的预检的。简单请求必须是满足以下三个条件:
- 请求方法:GET、HEAD、POST
- 请求标头:Accept、Accept-Language、Content-Language
- Content-Type:application/x-www-form-urlencoded、multipart/form-data、text/plain
-
非简单请求在发出真正请求前,浏览器会使用该OPTIONS方法向另一个源上的资源发送HTTP请求,以确定实际请求是否可以安全发送。只有在预检请求完成后,才发送真正的请求。
带凭据的请求
- 因为预检请求是不得包含凭据,所以服务端需要配置
Access-Control-Allow-Credentials: true
,表示可以使用凭据进行实际请求。 Access-Control-Allow-Origin
不能设置为*,需要指定明确的域名。Access-Control-Allow-Headers
不能设置为*,需要指定明确的标头。Access-Control-Allow-Methods
不能设置为*,需要指定明确的请求方法。
带凭据请求的nginx的配置示例
# 正则匹配对应的域名作为Access-Control-Allow-Origin的值
# 在http的层级下配置
http {
map $http_origin $allow_origin {
~^https?://(.+\.com\.cn|localhost:\d\{1,5\})$ $http_origin;
default '';
}
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $allow_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' $allow_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
}