springCloud项目解决跨域问题

2022/2/5 6:12:30

本文主要是介绍springCloud项目解决跨域问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

通过 spring cloud gateway 实现,

方式一:选择在主启动类中注册 CorsWebFilter 类:

/**
 * 1.允许cookies跨域
 * 2.允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
 * 3.允许访问的头信息,*表示全部
 * 4.预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
 * 5.允许提交请求的方法,*表示全部允许
 *
 * @return 返回 reactive 包下的 CorsWebFilter 对象
 */
@Bean
public CorsWebFilter corsWebFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.setMaxAge(3600L);
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsWebFilter(source);
}

 

方式二:在配置中实现

server:
  port: 8080

spring:
  application:
    name: online-course-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置 Nacos 地址
    # 路由转发: 意思是只要是以 /system 开头的路径都转发到 9001: 这样就可以做到对外隐藏,表面上访问的是 9000 实际上是 9001
    gateway:
      routes:
        - id: system
          uri: lb://online-course-system
          predicates:
            - Path=/system/**
        - id: business
          uri: lb://online-course-business
          predicates:
            - Path=/business/**
      # 全局跨域
      globalcors:
        # 跨域配置(可以在代码里面处理允许跨域,也可在这里全局处理)
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowCredentials: true
            allowedMethods:
              - GET
              - POST
              - OPTIONS
              - DELETE
              - PUT
              - HEAD
              - PATCH

 



这篇关于springCloud项目解决跨域问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程