Springboot整合swagger2项目的部署问题

转自:http://blog.sina.com.cn/s/blog_13b4eadda0102xaam.html




最近写了一个小项目,后端是springboot来搭建环境架构,前端是用ionic。要求是前后端分离开发,为了不想写接口文档就整合了swagger2。在这个过程中遇到了很多坑。

其中一个就是在本地服务器好好运行的项目,但是部署到自己的云服务器就抛出了拒绝访问错误。
MLHttpRequest cannot load http://127.0.01/api/user/logout. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.
这说明不能加载这个链接,跨域了。然后会去想如何解决跨域问题。其实关键点在swagger-ui自动生成接口文档链接的原理。
当项目部署到云服务器时,接口的链接应该是http://服务器地址:端口/资源地址,但是接口生成链接为127.0.0.1,说明swagger默认配置了为本地地址,即localhost。
swagger原理是根据@RestController("")中的资源地址,拼接上一个前缀,生成最终的接口来链接。因此,在部署到云服务器时,配置前缀为服务器的地址就好了。
方法一:在application.yml中配置sop.swagger.host
Springboot整合swagger2项目的部署问题


Springboot整合swagger2项目的部署问题
这样子就可以了。
Springboot整合swagger2项目的部署问题


Springboot整合swagger2项目的部署问题
前面的设置只是可以用swagger-ui来测试自己的接口,把接口部署到云服务器后,前端开发人员,将在前端页面调用接口来测试,还是存在跨域的问题。这是就要设置一个响应头response.setHeader("Access-Control-Allow-Origin", "*");来实现java的跨域访问。
定义一个拦截器:
@Component
public class CORSInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 添加跨域CORS
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
return true;
}
}


拦截器配置到web.xml中
下面使用的是springboot的配置
@Configuration
public class CrossDomain extends WebMvcConfigurerAdapter {
@Autowired
private CORSInterceptor corsInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor);
}
}

Springboot整合swagger2项目的部署问题