如何在Swagger中将<host:port>更改为域名

4

enter image description here

在这张图片中,Swagger请求使用了主机和端口,因此浏览器控制台会显示“XMLHttpRequest无法加载http://115.159.22.159:9001/bp/api/v1/user/1。请求的资源未包含'Access-Control-Allow-Origin'头信息。因此,来自'http://twogoods.cc'的源被禁止访问。”如何解决?
2个回答

3
@Bean
public Docket categoryApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .host("twogoods.cc")
            .groupName("bookplatform-api")
            .apiInfo(apiInfo())
            .select()
            .paths(apiPaths())
            .build()
            .directModelSubstitute(java.sql.Timestamp.class, java.sql.Date.class)
            .enableUrlTemplating(false);
}

host() method!!!


2
现在我知道host()方法可以改变“试一试”的URL了,但我还有一个问题:如何自动获取主机(就像HttpServletRequest.getServerName()一样),而不是手动输入?而且我不想从配置中获取特定的主机。 - Randy Lam

1
你可以使用 host(..)protocols(..) 方法,来覆盖默认值。

例如:

@Bean
public Docket customImplementation() {
    return new Docket(DocumentationType.SWAGGER_2)
        .protocols(Collections.singleton("https"))
        .host("twogoods.cc")
        .select()
        .build();
}

有没有想法可以动态地完成,例如根据实际域名选择主机名,这样在部署到各种环境时就不需要进行更改了? - vijayakumarpsg587
@Joey587 - 不确定,但你可能有三个选项(按可行性顺序,*未经测试): a)使用环境变量在启动时外部配置域名。 b)延迟初始化“Docket”bean,并使用收到的第一个[Host]标头来配置bean。 c)获取外部IP地址并进行反向查找(这里有风险)。 - Nick Grealy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接