跨域请求异常:The 'Acess-Control-Allow-Origin' header contains multiple values '*, *". but only one is allowed

目录
[隐藏]

1. 问题

在浏览器中进行跨域请求一个接口时报错如下:

Access to XMLHttoRequest at ‘https://xxx.lzw.me/abc/getToken from origin “http://localhost:3001 has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Acess-Control-Allow-Origin’ header contains multiple values ‘*, *”. but only one is allowed.

2. 原因

从报错信息上理解,是 Acess-Control-Allow-Origin 的值为 *, *,设置了多个。从 nginx 配置上查看设置的值是 *。以非跨域的方式请求该接口,则可以在 Response 中看到 header 信息中包含了两个 Acess-Control-Allow-Origin 的设置。那么原因就是在 nginx 之外的其它网关或应用程序中还设置了该 header 值。找到它并移除个性化的设置逻辑即可。

3. 解决方法

  • 如果 nginx 出口网关的设置是多余的,CORS 在应用程序层已有管理,则可以直接移除此处的配置。
  • 如果是应用程序内部针对该接口添加了设置,考虑到需支持允许所有接口跨域访问,应修改应用程序移除相关逻辑。
  • 如果希望在 nginx 层作统一配置管理,也可在应用程序出口网关层作 header 过滤。例如针对 Spring zuul 网关的设置实例:
server:
  port: 8080
spring:
  application:
    name: xxx-gateway
  main:
    allow-bean-definition-overriding: true
zuul:
  sensitive-headers: Access-Control-Allow-Origin
  ignored-headers: Access-Control-Allow-Origin,Token,APPToken
点赞 (0)

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code