代码地址

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的跨域配置封装了一下

  1. spring:
  2. cloud:
  3. gateway:
  4. globalcors:
  5. cors-configurations:
  6. '[/**]':
  7. allowedOrigins: "*"
  8. allowedMethods:
  9. - GET
  10. - POST
  11. - DELETE
  12. - PUT
  13. - OPTION

通过java配置的方式

这个就是spring的跨域,和Gateway没有啥关系

  1. @Configuration
  2. public class CorsConfig {
  3. @Bean
  4. public CorsWebFilter corsFilter() {
  5. CorsConfiguration config = new CorsConfiguration();
  6. config.addAllowedMethod("*");
  7. config.addAllowedOrigin("*");
  8. config.addAllowedHeader("*");
  9. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
  10. source.registerCorsConfiguration("/**", config);
  11. return new CorsWebFilter(source);
  12. }
  13. }

前端页面代码

user.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
  7. </head>
  8. <body>
  9. <div >
  10. <table border="1">
  11. <thead>
  12. </thead>
  13. <tbody id="userlist">
  14. </tbody>
  15. </table>
  16. </div>
  17. <input type="button" value="触发按钮" onclick="getData()">
  18. <script>
  19. function getData() {
  20. $.get('http://localhost:8888/order/demo01',function(data){
  21. alert(data);
  22. });
  23. }
  24. </script>
  25. </body>
  26. </html>

直接双击浏览器打开
image.png

测试

配置跨域之前:

点击 触发按钮 报跨域错误

image.png

配置跨域之后:

点击 触发按钮

console没有报错,并且弹出来东西了
image.png