3

有人可以告诉我为什么会出现这些错误。

 GET http://127.0.0.1:9000/api-docs/service.json

  200 OK 4ms    swagger-ui.js (line 30261)
  Unable to Load SwaggerUI  /api-docs/ (line 83)
  Cross-Origin Request Blocked: The Same Origin Policy disallows 
  reading the remote resource at http://127.0.0.1:9000/api-
   docs/service.json. This can be fixed by moving the resource to the 
  same domain or enabling CORS.
  uncaught exception: Can't read from server. It may not have the 
 appropriate access-control-origin settings.

我正在尝试在端口 9090 上运行 Swagger UI,在 9000 上运行 Swagger API 文档,并尝试在 UI 中显示文档。

我在 API 文档服务器(端口 9000)上添加了 CORS 过滤器,如下所示。

 FilterHolder cors = swaggerUIContext.addFilter(CrossOriginFilter.class,"/*",EnumSet.of(DispatcherTyp‌ e.REQUEST)); 
cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");       
cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, ""); 
cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD"); 
 cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type, api_key, Authorization"); 

firefox V33.0 中的 Request 和 Response 标头是

 Response Headers
   Content-Length   428
   Content-Type application/json

   Request Headers
     Accept application/json;charset=utf-8,*/*
     Accept-Encoding    gzip, deflate
     Accept-Language    en-US,en;q=0.5
     Connection keep-alive
     Host   localhost:9000
    Origin  http://localhost:9090
    Referer http://localhost:9090/api-docs/
     User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:33.0)       
    Gecko/20100101 Firefox/33.0

这是我在服务器上设置 CORS 的方式

       final ResourceHandler swaggerUIResourceHandler = new ResourceHandler();
    swaggerUIResourceHandler.setResourceBase("target/classes/api-docs");
    final ServletContextHandler swaggerUIContext = new ServletContextHandler();
    swaggerUIContext.setContextPath("/api-docs");
    swaggerUIContext.setHandler(swaggerUIResourceHandler);

    FilterHolder cors = swaggerUIContext.addFilter(CrossOriginFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type, api_key, Authorization");

    ServletHolder def = new ServletHolder("default", DefaultServlet.class);
    def.setInitParameter("resourceBase","./http/");
    def.setInitParameter("dirAllowed","false");
    swaggerUIContext.addServlet(def,"/");

    HandlerList handlers = new HandlerList();

handlers.setHandlers(new Handler[] { swaggerUIContext, new DefaultHandler() });
server.setHandler(handlers);
4

6 回答 6

2

你对 json 文件做了什么奇怪的事情吗?

我在尝试修改我的 JSON 文件并在 Chrome 上查看更改时遇到了同样的错误。确保 json 本身没有以某种方式破坏,额外的括号、逗号等。我从 swagger 现场演示中的一个示例 json 从头开始​​,我很好。我知道这是一项任务,但对我有用,至少加载了 UI!

您还可以浏览 swagger ui 自述文件,CORS 支持部分

于 2016-04-06T13:55:30.963 回答
1

通过将以下方法添加到我的应用程序中,我能够使其工作。请注意,这也会打开 API,以便您可以接受 CrossOrigin 请求。位的细节由addMapping()你决定,但这个例子从任何地方都可以打开一切。这是完整的课程。

@SpringBootApplication
@EnableSwagger2
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
      }
    };
  }
}
于 2018-05-10T19:48:32.443 回答
1

如果您使用的是 Spring Security

请添加此代码。

@Override
protected void configure(HttpSecurity http) throws Exception {
    
    http.cors().configurationSource(request -> 
        {
            CorsConfiguration cors = new CorsConfiguration();
                cors.setAllowedMethods(
                    Arrays.asList(HttpMethod.DELETE.name(),HttpMethod.GET.name(), HttpMethod.POST.name()));
                cors.applyPermitDefaultValues();
            
            return cors;
        
        }).httpBasic(); 

}

解释:

在上面的 CorsConfiguration 类中,我使用了两种方法。

  1. cors.applyPermitDefaultValues();

  2. cors.setAllowedMethods(请求类型名称列表);

这个方法 cors.applyPermitDefaultValues(); 将允许所有主机的跨源请求。通常此方法支持对这 3 种请求类型方法 GET、HEAD 和 PUT 的跨域支持。

如果您的 API 公开 PUT 、 DELETE 或任何其他请求方法。然后你需要用这个 cors.setAllowedMethods(); 覆盖它

于 2019-04-13T14:38:21.483 回答
0

我也遇到了这个问题,在检查了宠物商店示例中的标题后,我发现“Access-Control-Allow-Headers”需要“Content-Type、api_key、Authorization”。

确保你有api_key以及我丢失的那个。

于 2018-10-26T06:21:07.223 回答
0

我刚刚遇到了类似的问题:Swagger UI: HTTP Content-type "application/json" cause "Unable to Load SwaggerUI"

尝试将 GET service.json 响应的 HTTP Content-type 标头从“application/json”更改为“text/html”,甚至将其删除。我不知道为什么,但它似乎对Swagger UI有所不同。

于 2016-03-30T09:50:47.087 回答
0

对于 Springdoc OpenAPI,以下修复问题:@OpenAPIDefinition(servers = {@Server(url = "/", description = "Default Server URL")})

于 2022-01-17T19:22:28.897 回答