has been blocked by CORS policy: The ‘Access-Control-Allow-Origin‘ header contains multiple values ‘

控制台错误如下:

Access to XMLHttpRequest at 'https://xxx/xxx' from origin 'https://xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Access to XMLHttpRequest at 'https://xxx/xx' from origin 'https://xxx' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

原因:项目中设置了双跨域配置导致的问题

解决方法:

删除或注解掉一处,只保留一个。

注释掉nginx上的相关配置

    location / {
		root /var/www/html/xxx/dist/;
		index index.html;

		# 配置响应请求
		try_files $uri $uri/ /index.html$is_args$args;
	}
	location /api/ {
		proxy_pass http://localhost:xx/;
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Credentials' 'true';
		add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
		add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
		if ($request_method = 'OPTIONS') {
			add_header 'Access-Control-Max-Age' 1728000;
			add_header 'Content-Type' 'text/plain; charset=utf-8';
			add_header 'Content-Length' 0;
			return 204;
		}

后端代码不动

之后又出现 CORS 头缺少 'Access-Control-Allow-Origin' 跨域问题

已拦截跨源请求:同源策略禁止读取位于 https://xxx 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。状态码:204。

已拦截跨源请求:同源策略禁止读取位于 https://xxx 的远程资源。(原因:CORS 请求未能成功)。状态码:(null)。

发现还是报错,对nginx配置文件进行如下修改:

    location /api/ {
		proxy_pass http://localhost:xx/;
		if ($request_method = 'OPTIONS') {
			add_header 'Access-Control-Max-Age' 1728000;
			add_header 'Content-Type' 'text/plain; charset=utf-8';
			add_header 'Content-Length' 0;
			return 204;
		}
	}
	location / {
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Credentials' 'true';
		add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
		add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
		root /var/www/html/xxx/dist/;
		index index.html;

		# 配置响应请求
		try_files $uri $uri/ /index.html$is_args$args;
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值