温馨提示×

Linux Swagger如何调试

小樊
43
2026-08-05 21:18:08
栏目: 智能运维

在 Linux 下调试 Swagger(通常指 Swagger UI / OpenAPI),一般取决于你用的技术栈。下面按最常见场景给你一套「通用 + 实战」的调试思路。


一、明确你调试的是什么

先确认你属于哪一种:

场景 说明
✅ Swagger UI 打不开 页面 404 / 空白
✅ Swagger 接口返回 404 / 500 API 文档接口异常
✅ Swagger 参数不显示 注解或配置问题
✅ Swagger 请求失败 CORS / 鉴权 / 代理
✅ Swagger 不更新 缓存或配置未生效

二、最通用的调试流程(强烈推荐)

1️⃣ 确定 Swagger JSON 是否正常

Swagger UI 本质只是渲染一个 JSON:

# 常见地址
curl http://localhost:8080/v2/api-docs
curl http://localhost:8080/v3/api-docs

✅ 正常:返回 JSON
❌ 异常:接口本身有问题(不是 UI 问题)


2️⃣ 浏览器开发者工具(最关键)

在 Linux 下用 Chrome / Edge / Firefox:

  • 打开:F12
  • 查看:
    • Network:是否加载 swagger-ui 资源
    • Console:是否有 JS 报错
    • Response:接口返回内容

常见错误:

  • Failed to load API definition
  • CORS error
  • 401 Unauthorized

3️⃣ 查看后端日志(最重要)

Swagger 本质上由后端生成:

# Spring Boot
tail -f logs/app.log

# Node.js
pm2 logs

重点看:

  • 启动阶段是否加载 Swagger
  • 是否被拦截器 / 安全框架拦截

三、常见技术栈调试示例


✅ Spring Boot + Swagger(最常见)

1. 检查依赖

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.x.x</version>
</dependency>

2. 访问地址

http://localhost:8080/swagger-ui.html
http://localhost:8080/swagger-ui/index.html

3. 常见错误 & 解决

❌ 404

✅ 检查:

@Configuration
public class SwaggerConfig {
}

✅ 是否被拦截:

spring.mvc.static-path-pattern=/**

❌ 401 / 403

✅ Spring Security 放行:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
      .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll();
}

❌ CORS 错误

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

✅ Node.js / Express + swagger-ui-express

1. 访问地址

http://localhost:3000/api-docs

2. 检查 swagger.json

curl http://localhost:3000/swagger.json

3. 常见错误

  • JSON 不合法(用 jsonlint 检查)
  • 路径写错
  • YAML 格式错误

✅ Docker + Linux 环境

1. 检查端口映射

docker ps

✅ 确认:

-p 8080:8080

2. 进入容器调试

docker exec -it 容器名 /bin/bash
curl localhost:8080/v3/api-docs

四、Linux 常用调试命令速查

# 查看端口
ss -lntp | grep 8080

# 查看进程
ps -ef | grep java

# 查看日志
tail -f app.log

# 测试接口
curl -v http://localhost:8080/v3/api-docs

五、快速自检清单 ✅

  • [ ] swagger-ui 页面能打开
  • [ ] /v2/api-docs/v3/api-docs 返回 JSON
  • [ ] 没有被 Spring Security / 拦截器拦截
  • [ ] 没有 CORS 错误
  • [ ] 后端日志无异常

六、如果你愿意,我可以直接帮你定位

你可以直接贴:

  1. ✅ 使用的技术(Spring Boot / Node / 其他)
  2. ✅ Swagger 版本
  3. ✅ 报错截图或日志
  4. ✅ 访问的 URL

我可以一步一步帮你把问题定位到具体配置或代码

0