代码地址
https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_Gateway/demo09
后端代码配置
通过yml配置的方式
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration
Gateway对spring的跨域配置封装了一下
spring:cloud:gateway:globalcors:cors-configurations:'[/**]':allowedOrigins: "*"allowedMethods:- GET- POST- DELETE- PUT- OPTION
通过java配置的方式
这个就是spring的跨域,和Gateway没有啥关系
@Configurationpublic class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}}
前端页面代码
user.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script></head><body><div ><table border="1"><thead></thead><tbody id="userlist"></tbody></table></div><input type="button" value="触发按钮" onclick="getData()"><script>function getData() {$.get('http://localhost:8888/order/demo01',function(data){alert(data);});}</script></body></html>
直接双击浏览器打开
测试
配置跨域之前:
点击 触发按钮 报跨域错误

配置跨域之后:
点击 触发按钮
console没有报错,并且弹出来东西了
