nginx跨域+vue的withCredentials

vue中配置了

axios.defaults.withCredentials = true

服务器在header中响应的是

access-control-allow-orgin: *

在vue中如上设置了withCredentials=true后,请求时需要指定路径或者服务器进行指定路径的修改,在nginx中的配置文件主要设置如下规则,其它header项根据业务需要配置

主要是add_header 'Access-Control-Allow-Origin' $http_originadd_header 'Access-Control-Allow-Credentials' true

location ^~ /{
	add_header 'Access-Control-Allow-Origin' $http_origin; #这里必须指定为$http_orgin,明确指定可以跨域请求的域名,替代*
	add_header 'Access-Control-Allow-Headers' 'Cookie, DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
	add_header 'Access-Control-Allow-Credentials' true;#此项配合上一个header携带cookie等信息
	add_header 'Access-Control-Allow-Methods' "GET,POST,PUT,DELETE,OPTIONS";
	if ($request_method = 'OPTIONS'){
            return 204; #预检请求返回此code
	}
....
......
........
..........
}

注意:请求头里不能有多个 Access-Control-Allow-Origin ,否则会导致无法访问

posted @ 2022-01-12 17:59  阿伦啊  阅读(726)  评论(0编辑  收藏  举报