我们在二十四、springCloudAlibaba-gateway整合nacos搭建了gateway的网关案例,在此基础上,来试下跨域请求处理。
1、跨域问题
正常我们ajax请求某个域名,若是页面所在域名跟请求的域名不一致,且请求的方法未开启跨域访问,则会报错,比如这里有一个页面
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
...<button onclick="add()">下单</button>...function add(){$.ajax({url:'http://localhost:8088/order-service/order/add',data:{},type:"GET",error: function() {alert("网络异常,请重试");},success:function(data){alert(data);}});}
我们用IDEA带的工具打开这个页面(就不搞nginx了)
启动网关和order服务,点击服务
然后我们加上跨域试试!
2、gateway提供了两种方式
配置文件
gateway:#路由规则routes:- id: order_route # 路由的唯一标识uri: lb://order-service #需要转发的地址.lb本地负载均衡策略#断言规则 用于路由规则的匹配predicates:- Path=/order-service/**#- Query=green,hel.#- MyCustomize=test#- After=2023-11-13T21:05:39.811+08:00[Asia/Shanghai]#匹配请求http://localhost:8088/order-service/order/add#过滤器 用于过滤请求filters:- StripPrefix=1 #转发之前去掉第一层路径- AddRequestHeader=X-Request-red, blue- AddRequestParameter=red, blue- MyCustomize=from,suibibk.com#http://localhost:8010/order/add#- id: stock_routeglobalcors:cors-configurations:'[/**]': #允许跨域访问的资源allowedOrigins: "*" #跨域来源allowedMethods:- GET- POST
只需要加上配置
globalcors:cors-configurations:'[/**]': #允许跨域访问的资源allowedOrigins: "*" #跨域来源allowedMethods:- GET- POST
就可以解决跨域了
配置类方式
package com.suibibk.springCloud.gateway;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.reactive.CorsWebFilter;import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;import org.springframework.web.util.pattern.PathPatternParser;@Configurationpublic class CorsConfig {@Beanpublic CorsWebFilter corsWebFilter(){CorsConfiguration config = new CorsConfiguration();config.addAllowedHeader("*");//允许的请求头参数config.addAllowedMethod("*");//允许的方法config.addAllowedOrigin("*");//允许的来源UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**",config);return new CorsWebFilter(source);}}
这里要记得引用的类所在包为reactive
上面两种方法任选一种都可以,然后我们再试试
就正常了
ok!
