Swagger跨域

什么是跨域

跨域是指从一个域名的网页去请求另一个域名的资源。比如从www.baidu.com 页面去请求 www.google.com 的资源。跨域的严格一点的定义是:只要 协议,域名,端口有任何一个的不同,就被当作是跨域。
ref: 跨域与跨域访问

  • 跨域与否是在浏览器端:
    这里写图片描述

  • 服务器之间的调用不是跨域:
    这里写图片描述

Swagger跨域

这里写图片描述

Solution

在swagger应用的服务器上使用代理。
比如Swagger应用在服务器A,其域名为swagger;Other应用在服务器B,其域名为other。改动如下:

在服务器A上使用代理,代理映射规则:swagger/api/* -> other/*
Swagger设置调试的接口在Swagger应用

这里写图片描述
这样就可以解决跨域问题。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Spring Boot中放行Swagger,需要进行以下步骤: 1. 添加Swagger依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 2. 创建Swagger配置类: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 3. 添加全局跨域配置: ```java @Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } } ``` 其中,`config.addAllowedOrigin("*")`表示允许所有来源访问Swagger API。如果需要限制来源,可以将`*`替换为具体的域名。然后将`CorsFilter`添加到Spring Security配置中即可。 4. 在`application.properties`文件中添加以下配置: ```properties spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 ``` 这样就可以使用Swagger UI查看API文档了。访问路径为:`http://localhost:8080/swagger-ui.html`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值