我试图在我的项目中设置招摇。
我有以下SwaggerConfiguration类:
@EnableSwagger
@Configuration
@ComponentScan(basePackages = {"my.package"})
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
SwaggerSpringMvcUi.WEB_JAR_RESOURCE_PATTERNS)
.addResourceLocations(
SwaggerSpringMvcUi.WEB_JAR_RESOURCE_LOCATION)
.setCachePeriod(0);
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(SwaggerSpringMvcUi.WEB_JAR_VIEW_RESOLVER_PREFIX);
resolver.setSuffix(SwaggerSpringMvcUi.WEB_JAR_VIEW_RESOLVER_SUFFIX);
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
不幸的是,我无法从服务器上读取内容。它可能没有适当的访问控制源设置。
经过快速研究后,我发现我需要添加CORSFilter来克服这个问题:
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
我使用CURL检查 - 标题已正确修改,但Swagger仍然无法正常工作(与之前相同的错误消息)。
有什么想法吗?
答案 0 :(得分:1)
请查看最新发布的Spring Boot 1.3.M1: https://spring.io/blog/2015/06/12/spring-boot-1-3-0-m1-available-now
最近发布的Spring Framework 4.2 RC1为开箱即用的CORS提供了一流的支持,为您提供了比基于典型过滤器的解决方案更简单,更强大的配置方式。
...更多信息:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework