You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger无法跳转至外部URL问题求助:三种重定向方式均失败

Swagger调用外部重定向接口的CORS问题解决

问题场景

项目中Swagger可正常处理GET/POST/DELETE请求,但调用以下三种返回外部URL重定向的接口时,均出现错误:

public String testUrl = "https://www.google.com/";

@GetMapping("/RedirectView")
public RedirectView redirectView() {
    return new RedirectView(testUrl);
}

@GetMapping("/ResponseEntity")
public ResponseEntity<Object> responseEntity() throws URISyntaxException {
    URI uri = new URI(testUrl);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uri);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

@GetMapping(value = "/HttpServletResponse")
public void httpServletResponse(HttpServletResponse httpServletResponse) throws IOException {
    httpServletResponse.sendRedirect(testUrl);
}

执行后Swagger提示:

Code: Undocumented
Details: TypeError: Failed to fetch

控制台报错:

Access to fetch at 'https://www.google.com/' (redirected from 'http://localhost:8080/HttpServletResponse') from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

即便关闭项目自身的CORS配置,问题依然存在。

原因分析

这不是你项目的CORS配置问题——Swagger UI是通过AJAX/fetch请求调用接口,当接口重定向到外部域名时,外部站点(如google.com)并未配置允许http://localhost:8080跨域,浏览器的同源策略会直接拦截这个跨域重定向请求。你的项目CORS配置只针对自身接口的跨域访问,无法影响外部站点的CORS规则。

解决方案

1. 直接访问接口URL(最简便)

Swagger的"Try it out"按钮是用AJAX发起请求,会触发同源检查。直接复制接口的完整URL(如http://localhost:8080/RedirectView)到新浏览器标签页打开,浏览器会直接处理重定向,不受CORS限制。

2. 修改接口返回URL,手动跳转

不直接返回重定向响应,而是返回外部URL,在Swagger中拿到URL后手动跳转:

@GetMapping("/getRedirectUrl")
public Map<String, String> getRedirectUrl() {
    Map<String, String> result = new HashMap<>();
    result.put("redirectUrl", testUrl);
    return result;
}

调用接口后,复制返回的redirectUrl到新标签页打开即可。如果是前端页面调用,可通过window.location.href = redirectUrl实现自动跳转,同样不会触发CORS问题。

3. 自定义Swagger UI脚本处理重定向

如果需要在Swagger内自动完成跳转,可以自定义Swagger UI的JavaScript,拦截重定向响应并直接跳转:

  1. 在项目静态资源目录(如src/main/resources/static)下创建custom-swagger.js:
window.addEventListener('load', () => {
  const originalFetch = window.fetch;
  window.fetch = (resource, options) => {
    return originalFetch(resource, options).then(response => {
      if (response.redirected) {
        window.location.href = response.url;
        return new Response(null, { status: 200 });
      }
      return response;
    });
  };
});
  1. 在Swagger配置中引入该脚本(以SpringDoc为例):
@Bean
public OpenAPI customOpenAPI() {
  return new OpenAPI()
          .info(new Info().title("API Docs").version("v1"));
}

@Bean
public SwaggerUiConfigParameters swaggerUiConfigParameters() {
  SwaggerUiConfigParameters config = new SwaggerUiConfigParameters();
  config.setCustomJs("/custom-swagger.js");
  return config;
}

这样当Swagger调用重定向接口时,脚本会自动跳转到外部URL,绕过CORS限制。

4. 不推荐:设置请求为no-cors模式

可以配置Swagger让特定请求使用no-cors模式,但这种方式下浏览器会返回不透明响应,无法获取重定向后的内容,也不会触发页面跳转,仅能避免请求报错,实际意义不大。


内容的提问来源于stack exchange,提问作者zlobeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:52:50