zl程序教程

您现在的位置是:首页 >  后端

当前栏目

跨域问题:不允许有多个 'Access-Control-Allow-Origin' CORS 头

跨域 问题 &# 多个 access 允许 Control x27
2023-06-13 09:11:14 时间

好久没有更新了,记录一个小问题

“问题描述: 已拦截跨源请求:同源策略禁止读取位于 http://localhost:9015/standard-service/standard/add 的远程资源。(原因:不允许有多个 'Access-Control-Allow-Origin' CORS 头)。

直接请求出现时上述问题,不允许多个 'Access-Control-Allow-Origin' CORS 头 出现,当时的跨域配置包含多处。

背景

解决方案项目后端使用了多个服务模块,对外通过 gateway 网关进行暴露以及请求的分发;前端在请求的时候直接请求网关接口,然后网关将请求分发到独立模块中去。

在此请求过程中,因为搬运了之前的一个模块,而后在前端请求时出现了上述问题。其中涉及到的跨域配置如下。

请求过程

gateway网关配置文件

spring:
 cloud:
        # 微服务网关
        gateway:
          discovery:
            locator:
              enabled: true                 # 开启从注册中心动态创建路由的功能,利用微服务名进行路由
              lower-case-service-id: true   # 微服务名称以小写形式呈现

          globalcors:
            cors-configurations: 
              # 全局允许访问
              '[/**]':
                allow-credentials: true
                allowed-origins:
                  - http://localhost:8080
                  - http://standard.beatree.cn
                allowed-headers: "*"
                allowed-methods:
                  - OPTIONS
                  - GET
                  - POST
                  - PUT
                  - DELETE

service功能模块全局跨域配置

CorsConfig.java

//@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Autowired
    CorsParams corsParams;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(corsParams.getAllowedOrigins())
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}
/**
 *  corsParams.getAllowedOrigins() 
 */

application.yml

cros:
  allowedOrigins:
    - http://api.beatree.cn
    - http://localhost:8080

问题现象

解决方案

问题: 如上,出现了重复配置的问题,当去除掉子模块中的 allowedOrigins 会403forbidden问题。

解决方案: 不需要通过两个模块都进行跨域的配置,可仅在 gateway 网关模块进行设计即可;从而避免重复配置产生的问题。