Files
easygoadmin-wiki/EasyGoAdmin_Gin_EleVue/zh/api-spec/response.md
T
2026-10-25 17:24:27 +08:00

95 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 8.1 统一响应格式
:::tip 概述
所有接口返回统一 JSON 信封。对外业务码只有三种:**0 成功、1 失败(msg 说明原因)、401 未认证**——前端判断零歧义,详细原因经 msg 透出。
:::
## 信封结构
```typescript
interface Res {
code: number; // 0=成功,1=失败,401=登录过期
ok: boolean; // 是否成功
msg: string; // 提示信息
data: any; // 数据(无数据为 null 或 {})
}
```
## 成功
```json
{
"code": 0,
"ok": true,
"msg": "操作成功",
"data": {
"id": 1,
"username": "admin"
}
}
```
自定义成功文案用 `OkMsg(msg, data)`(如导入结果提示)。
## 分页
```json
{
"code": 0,
"ok": true,
"msg": "操作成功",
"data": {
"records": [ { "id": 1, "name": "示例" } ],
"total": 100,
"size": 20,
"current": 1,
"pages": 5
}
}
```
records 为空时输出 `[]` 而非 null(NewPageData 保证)。
## 失败
```json
{ "code": 1, "ok": false, "msg": "案例名称已存在", "data": {} }
```
## 未认证
```json
{ "code": 401, "ok": false, "msg": "登录已过期,请重新登录", "data": {} }
```
401 **原码透出**(不映射为 1),前端据此跳登录页。
## 码映射规则(后端内部 → 对外)
后端内部错误码丰富(400/403/429/1001…,见 [8.2 错误码对照表](/zh/api-spec/error-code.html)),经 response.Fail 统一收敛:
```text
内部 401 → 对外 401(原样,触发前端跳登录)
其余非 0 → 对外 1(msg 取内部码的中文消息)
```
这样前端只需三分支:`code===0` 成功 / `code===401` 跳登录 / 其余弹 msg。
## HTTP 状态码
响应体 code 与 HTTP 状态码同步(写信封时按 code 定状态),非 2xx 时响应体仍是 JSON 信封——不存在裸错误页。
## 构造 API(后端)
| 函数 | 用途 |
|---|---|
| response.Ok(data) | 成功 |
| response.OkMsg(msg, data) | 成功 + 自定义文案 |
| response.Page(list, total) | 分页 |
| response.Fail(err) | 失败(apperr 按码,其余通用 1) |
| response.FailCode(base, format, args) | 指定错误码 + 格式化消息 |
## 下一步
→ [8.2 错误码对照表](/zh/api-spec/error-code.html)