Zuul网关之跨域支持

API网关
01 Spring Cloud Gateway网关之快速上手
02 Spring Cloud Gateway网关之两种路由配置方式
03 Spring Cloud Gateway网关之跨域支持
04 Spring Cloud Gateway网关之自定义全局过滤器
05 Spring Cloud Gateway网关之自定义路由过滤器
06 Spring Cloud Gateway网关之自定义路由谓词工厂
07 Spring Cloud Gateway网关之超时时间配置
08 Spring Cloud Gateway网关之配置说明
09 Zuul网关之快速上手
10 Zuul网关之路由配置
11 Zuul网关之跨域支持
12 Zuul网关之自定义过滤器
13 Zuul网关之超时时间配置

一 Zuul网关如何支持跨域

默认情况下,Zuul将所有跨域请求(CORS)路由到服务。如果您希望Zuul处理这些请求,可以通过提供自定义WebMvcConfigurer bean来完成:

具体如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}

二 验证跨域支持情况

模拟前准备:

  • 打开控制台随便打开一个域名如 https://baidu.com

  • 引入jquery并设置为同步

    1
    2
    3
    4
    5
    6
    7
    8
    var importJs=document.createElement('script') //在页面新建一个script标签
    importJs.setAttribute("type","text/javascript") //给script标签增加type属性
    importJs.setAttribute("src", 'https://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js') //给script标签增加src属性, url地址为cdn公共库里的
    document.getElementsByTagName("head")[0].appendChild(importJs) //把importJs标签添加在页面

    $.ajaxSetup({
    async: false
    });

在未配置跨域之前执行以下js请求网关接口并观察结果:

1
2
var result = $.get('http://localhost:8888/business/test1');
console.log(result.responseText)

出现以下报错

1
2
3
Access to XMLHttpRequest at 'http://localhost:8888/business/test1' from origin 'http://localhost:9999' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET http://localhost:8888/business/test1 net::ERR_FAILED

具体报错截图:

image-20200822235236181

配置跨域支持,观察结果

执行上一步相同的js,可以看到正常的接口返回,并没有出现跨域问题:

image-20200822235522851