mcpField
D
debug-fe-be-integration

debug-fe-be-integration

github.com/kensaurus开发941 次安装2 周前更新
代码仓库

关于 debug-fe-be-integration

面向编码 Agent 的前后端集成排错技能,通过请求证据、日志、 schema 和两端代码追踪问题。它帮助开发者归类错误,并围绕 API 契约提出对应修复。

主要功能

  1. 01识别前后端技术栈
  2. 02归类 API 集成错误
  3. 03跨两端代码追踪请求
  4. 04结合日志与生产错误证据
  5. 05为两端提出针对性修复

适用场景

  1. 01排查失败的 API 请求
  2. 02定位前后端契约不一致
  3. 03分析验证、认证或 CORS 错误

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kensaurus/skills --skill debug-fe-be-integration

安装后在 Claude Code 中输入/debug-fe-be-integration确认已加载。

详细介绍

前端-后端集成调试技能

自由度:混合。 哪一侧有问题[自由度高]; 双侧追踪探测[自由度低 — 按原样运行]。

通过分析后端日志、生产环境错误和源代码,系统地调试前后端集成问题,找出根本原因并修复两侧。

推理方法

  1. 观察 — 状态、载荷、验证错误、双方日志
  2. 解读 — FE 漏传字段,还是 BE 模式漂移,或者是身份验证/CORS
  3. 分类 — 缺少参数 / 类型 / 404 / 401 / 500 / CORS
  4. 评估严重程度 — 写入路径上的 500 比外观问题导致的 422 消息更严重

示例

观察: FE GET /api/reports → 500;BE 日志显示 ZodError: expected string, received undefined,出错字段为 year。 解读: FE 漏传了 year;BE 模式要求必须提供该字段,且没有默认值。 分类: 缺少参数 — 修复 FE 调用,并在 BE 中添加明确的 422 响应或默认值。 验证: 绑定年份后,同一请求返回 200;双方均已更新。

报告前自我检查

  • 已检查双方 — 查看 FE 调用和 BE 模式/日志,而非猜测其中一方
  • 明确指出契约 — 状态 + 载荷字段,而非笼统地说“双方不一致”
  • 修复符合问题类别 — 不要用 Zod 默认值来修复 404
  • 正确选择负责人 — 单层崩溃 → debug-error;主动审查契约 → audit-fe-api

步骤 0:自动检测技术栈

开始调试前,先了解项目架构。

0a. 检测前端框架

读取 package.json 并查找:

信号框架
nextNext.js
nuxtNuxt
@remix-run/reactRemix
@sveltejs/kitSvelteKit
vite + reactVite React SPA
@angular/coreAngular
0b. 检测后端框架
Glob: **/app/api/**/route.ts → Next.js App Router
Glob: **/pages/api/**/*.ts → Next.js Pages Router
Glob: **/server/api/**/*.ts → Nuxt server
Glob: **/src/routes/**/*.ts → Express/Hono/Fastify
Glob: **/src/app.ts or **/src/index.ts → Node backend entry
Glob: **/main.py or **/app.py → Python backend
Glob: **/main.go → Go backend
0c. 检测 API 风格和验证方式
信号技术
@trpc/servertRPC(类型安全,无需 REST 审计)
graphql 或 @apollo/serverGraphQL
BE 依赖中有 zodZod 验证
BE 依赖中有 joiJoi 验证
BE 依赖中有 yupYup 验证
class-validatorNestJS 风格的验证
pydanticPython Pydantic 验证
0d. 查找路由和控制器模式
Grep: pattern "router\.(get|post|patch|put|delete)" glob "*.{ts,js}" — Express-style
Grep: pattern "app\.(get|post|patch|put|delete)" glob "*.{ts,js}" — Hono/Express
Grep: pattern "export (async function |const )(GET|POST|PATCH|PUT|DELETE)" glob "**/route.ts" — Next.js
Grep: pattern "defineEventHandler" glob "*.{ts,js}" — Nuxt/H3
0e. 记录发现结果
STACK DISCOVERY:
- Frontend: [framework + version]
- Backend: [framework + version]
- API style: [REST / GraphQL / tRPC]
- Validation: [Zod / Joi / Yup / Pydantic / none]
- Route files: [pattern and locations]
- Controller files: [pattern and locations]
- Schema files: [pattern and locations]

步骤 1:研究调试模式

1a. Firecrawl — 集成调试

按原样搜索框架和验证库名称——认识名称不等于了解其当前 API 或错误格式。

firecrawl:firecrawl_search
{
 "query": "<FE_FRAMEWORK> <BE_FRAMEWORK> API integration debugging best practices [current year]",
 "limit": 5,
 "sources": [{ "type": "web" }]
}

其他有针对性的搜索:

主题查询
验证错误<VALIDATION_LIB> error handling API response best practices
CORS 问题<BE_FRAMEWORK> CORS configuration debugging
类型不匹配TypeScript API type safety frontend backend shared types
1b. Context7 — 框架文档
context7:resolve-library-id
{
 "libraryName": "<VALIDATION_LIB>",
 "query": "error handling error messages custom errors"
}

步骤 2:收集错误证据

2a. 检查 Sentry 中的生产环境错误
sentry:search_issues
{
 "organizationSlug": "<ORG_SLUG>",
 "query": "API integration errors 4xx 5xx validation from the last 7 days",
 "projectSlugOrId": "<PROJECT_SLUG>",
 "regionUrl": "<REGION_URL>",
 "limit": 25
}

如果项目为 FE 和 BE 分别配置了 Sentry 项目,请检查两者:

  • FE 项目:网络错误、API 调用引发的未处理拒绝
  • BE 项目:验证错误、未处理异常、500 错误
2b. 阅读后端终端日志

读取运行后端的终端输出(npm run dev 或同等命令)——在 Cursor 中查看 terminals/*.txt;在 Claude Code 中查看启动后端时使用的 shell 或日志文件。

查找最近 3-5 分钟内的错误:

  • 4xx 错误(400、401、403、404、422)
  • 5xx 错误(500、502、503)
  • ZodError / ValidationError — 验证失败
  • AppError / 自定义错误类
  • 堆栈跟踪
  • 警告消息
2c. 对发现的错误进行分类
类别日志模式根本原因
缺少参数ZodError: expected string, received undefinedFE 未发送必需参数
类型错误ZodError: invalid_typeFE 发送了错误类型
未找到端点404 /api/...FE 调用了不存在的端点
身份验证错误401 Unauthorized缺少或无效的令牌
权限错误403 Forbidden用户没有权限
验证错误422 Unprocessable请求正文无效
服务端错误500 Internal后端错误
CORS 错误CORS policy缺少 CORS 配置

第 3 步:追踪错误的源代码

3a. 将错误映射到端点

对于发现的每个错误,使用 Grep 定位:

前端调用:

Grep: pattern "<ERROR_ENDPOINT>" glob "*.{ts,tsx,js,jsx}"

后端路由:

Grep: pattern "<ERROR_ENDPOINT>" glob "*.{ts,js,py,go,rb}" — in backend source

验证架构:

Grep: pattern "z\.object|z\.string|z\.number" in the controller/route file
SemanticSearch: "validation schema for <ENDPOINT>" target: [backend directory]
3b. 阅读完整调用链

对于每个错误,阅读完整的请求调用链:

  1. 前端调用 — 阅读发起 API 调用的文件(服务、钩子或组件)
  2. API 客户端配置 — 阅读 axios/fetch 拦截器配置
  3. 后端路由 — 阅读路由处理程序
  4. 后端控制器 — 阅读控制器/服务逻辑
  5. 验证架构 — 阅读该端点的 Zod/Joi/Yup 架构
  6. 数据库查询 — 阅读数据库查询(如果错误与数据有关)
3c. 使用 Supabase MCP 验证数据状态

如果错误可能与数据有关:

supabase:execute_sql
{
 "query": "SELECT * FROM <TABLE> WHERE <CONDITION> LIMIT 5"
}

检查:

  • FE 所需的数据是否确实存在?
  • 枚举值是否正确?
  • 外键关系是否完整?
  • RLS 策略是否允许该用户访问?

第 4 步:生成修复建议

4a. 前端修复

对于每个错误,提供:

### Issue: [Endpoint] — [Error Type]

**Current FE Call:**
[show the actual code from Grep results]

**Correct FE Call:**
[show the fixed code]

**Why:** [explanation of required parameter/type/format]

**Files to Update:** [list specific files]
4b. 后端增强

对于每个错误,考虑后端改进,并在报告中给出建议。应用针对当前契约故障的修复;只有用户提出要求时,才实施稳健性增强,并且每次编辑都应尽可能精确。

### Backend Enhancement: [Endpoint]

**Current Behavior:** Returns 500 with cryptic validation error

**Recommended Enhancement:**
- Add default value for optional params
- Add clear error message for required params
- Add type coercion where appropriate
- Return helpful 422 instead of 500

后端增强模式示例:

// Before: bare schema, cryptic error on missing param
const schema = z.object({
 year: z.string(),
});

// After: defaults, coercion, clear errors
const schema = z.object({
 year: z.string({
 required_error: "year is required (format: YYYY)"
 }).default(() => new Date().getFullYear().toString()),
 page: z.coerce.number().default(1).int().positive(),
 limit: z.coerce.number().default(10).int().max(100),
});

第 5 步:后端稳健性检查清单

输入验证
  • 所有必需参数都有清晰的错误消息
  • 为可选参数设置合理的默认值
  • 在适当情况下进行类型转换(字符串转数字)
  • 范围验证(日期、数字)
  • 格式验证(电子邮件、UUID、日期字符串)
错误处理
  • 捕获并包装数据库错误
  • 提供可执行的错误消息(而不是“Internal Server Error”)
  • 记录包含上下文的错误(userId、端点、参数)
  • 不向客户端暴露内部细节(堆栈跟踪、SQL)
API 契约一致性
  • 响应结构保持一致({ data } 或 { error })
  • 状态码正确(200 表示成功,201 表示创建,204 表示删除)
  • 所有列表端点的分页格式保持一致
  • 日期格式保持一致(ISO 8601)
  • 错误响应结构保持一致

输出模板

## Frontend-Backend Integration Debug Report

**Analyzed:** [timestamp range]
**Frontend:** [framework]
**Backend:** [framework]
**API style:** [REST/GraphQL/tRPC]

---

### Production Errors (Sentry)

| Endpoint | Error | Events (7d) | Root Cause |
|----------|-------|-------------|------------|
| [endpoint] | [error msg] | [count] | [FE/BE/Data] |

---

### Backend Log Errors

| Endpoint | Method | Status | Error Type | Root Cause |
|----------|--------|--------|------------|------------|
| `/api/...` | GET | 500 | ZodError | Missing `year` param |
| `/api/...` | GET | 404 | Not Found | Endpoint not implemented |

---

### Critical Issues (Must Fix)

#### 1. [Endpoint] — [Status Code]
- **Error:** [error message]
- **Root Cause:** [explanation]
- **Frontend Fix:** [what FE needs to change, with code]
- **Backend Enhancement:** [optional BE improvement, with code]
- **Files:** FE: [path], BE: [path]

---

### Warnings (Should Fix)

#### 1. [Issue description]
- **Impact:** [what happens if not fixed]
- **Recommendation:** [how to fix]

---

### Backend Enhancements (Robustness)

#### 1. [Enhancement description]
- **Current:** [current behavior]
- **Recommended:** [better approach]
- **Benefit:** [why this helps]

---

### Research Findings Applied
- [Pattern from research]: [how it applies]
- [Best practice]: [gap identified]

---

### Summary Table

| Endpoint | Issue | Fix Required | Priority |
|----------|-------|--------------|----------|
| `/api/...` | Missing param | Frontend | HIGH |
| `/api/...` | No error handling | Both | MEDIUM |
| `/api/...` | Endpoint 404 | Remove or implement | LOW |

---

### Next Steps

1. [ ] Frontend fixes: [action items with files]
2. [ ] Backend enhancements: [action items with files]
3. [ ] Re-test: [verification steps]
4. [ ] Monitor: Check Sentry after deploy for regression

常见模式和修复方法

模式 1:缺少查询参数

症状: ZodError: expected string, received undefined

FE 修复: 将缺少的参数添加到 API 调用中。

BE 修复: 添加默认值或清晰的错误消息。

模式 2:未找到端点(404)

症状: 404 /api/endpoint-name

调试步骤:

  1. 在后端路由文件中使用 Grep 搜索端点路径
  2. 检查端点是否以其他名称存在
  3. 如果有 API 文档,请进行检查
  4. 决定:移除 FE 调用、修正拼写错误,或实现该端点
模式 3:服务失败(500)

症状: 500 Internal Server Error,且没有有用的消息

调试步骤:

  1. 阅读后端控制器,查找未处理的异常
  2. 检查服务是否妥善处理数据库错误
  3. 如果使用 Supabase,检查 RLS 策略(数据可能被阻止访问)
  4. 添加 try/catch,返回有意义的错误响应
模式 4:CORS 错误

症状: CORS policy: No 'Access-Control-Allow-Origin'

调试步骤:

  1. 检查后端 CORS 配置
  2. 验证允许的源、方法和标头
  3. 检查前端和后端的凭据模式是否一致
模式 5:重复 / 过时的请求

症状: 同一 API 被多次调用,或显示过时的数据

调试步骤:

  1. 检查是否配置了 TanStack Query / SWR 的 staleTime
  2. 检查变更操作后是否会使缓存失效
  3. 检查 queryKey 是否正确且唯一
  4. 检查组件重新挂载是否导致重新获取数据

与其他技能集成

  • audit-fe-api:从前端代码角度进行主动审计(先运行)。
  • debug-sentry-monitor:对生产环境中的 Sentry 错误进行分流和修复。
  • audit-db-schema:验证数据库架构是否符合 API 预期。

评论

支持 Markdown