cookie跨域状态共享

271 阅读1分钟

fetch 和 axios

fetch 参数设置: credentials: "include" 表示前端同意跨域cookie状态共享 axios 参数设置: withCredentials: true 表示前端同意跨域cookie状态共享

  • 当前端本地开发的时候a.com 跳转到b.com 前端设置了cookie共享,但是b.com(可以理解为服务端) 并没有设置接受状态共享
 // webpack 配置
 devServer: {
    headers: {
      "Access-Control-Allow-Origin": "http://localhost:8080", // 需要指定域名
      "Access-Control-Allow-Credentials": "true", // 同意跨域共享
    },
    port: "7300",
},
// vite 配置
server: {
  host: '0.0.0.0',
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:8080', // 需要指定域名
    'Access-Control-Allow-Credentials': 'true' // 同意跨域共享
  }
}
  • 如果是部署线上需要配置nginx
 server {
        listen      8080;
        server_name  localhost;

		#设置变量 $cors_origin
        set $cors_origin "";
		#请求地址匹配格式  用来控制http请求地址 设置跨域白名单
        if ($http_origin ~ "http://(.*).baidu.com$") {
            set $cors_origin $http_origin;              
        }	

        add_header Access-Control-Allow-Origin '$cors_origin';  // 需要指定域名
        add_header Access-Control-Allow-Credentials "true"; // 同意跨域共享
		add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
		add_header Access-Control-Allow-Headers  'token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,XRequested-With';
		if ($request_method = 'OPTIONS') {
			return 200;
		}
	
	location /appmains {
            proxy_pass http://appmainsserver;
        }

    }