[ PROMPT_NODE_24702 ]
network
[ SKILL_DOCUMENTATION ]
# 网络与 API 错误模式
常见的网络和 API 错误及其诊断与解决方案。
## HTTP 状态错误
### 400 Bad Request
HTTP 400 Bad Request
{"error": "Bad Request", "message": "Invalid JSON"}
**原因**:
1. JSON 主体格式错误
2. 缺少必需字段
3. 字段值无效
4. Content-Type 请求头错误
**诊断**:
bash
# 验证 JSON
echo '{"key": "value"}' | jq .
# 检查请求
curl -v -X POST https://api.example.com/endpoint
-H "Content-Type: application/json"
-d '{"key": "value"}'
**解决方案**:
javascript
// 检查 Content-Type
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // 不是 'text/plain'
},
body: JSON.stringify(data), // 不仅仅是 data
})
// 发送前验证
if (!data.required_field) {
throw new Error('Missing required_field')
}
---
### 401 Unauthorized
HTTP 401 Unauthorized
{"error": "Unauthorized", "message": "Invalid or expired token"}
**原因**:
1. 缺少身份验证令牌
2. 令牌过期
3. 令牌格式无效
4. 身份验证方案错误
**解决方案**:
javascript
// 检查 Authorization 请求头格式
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`, // 注意: "Bearer " 前缀
},
})
// 如果过期则刷新令牌
async function fetchWithAuth(url) {
let response = await fetch(url, {
headers: { 'Authorization': `Bearer ${accessToken}` }
})
if (response.status === 401) {
accessToken = await refreshToken()
response = await fetch(url, {
headers: { 'Authorization': `Bearer ${accessToken}` }
})
}
return response
}
---
### 403 Forbidden
HTTP 403 Forbidden
{"error": "Forbidden", "message": "Insufficient permissions"}
**原因**:
1. 已认证但未授权
2. 资源访问被拒绝
3. 速率限制
4. IP 被封禁
**与 401 的区别**: 401 = "你是谁?" 403 = "我知道你是谁,但不行。"
**解决方案**:
- 检查用户权限/角色
- 验证 API 密钥范围
- 检查速率限制请求头
- 验证 IP 白名单
---
### 404 Not Found
HTTP 404 Not Found
{"error": "Not Found", "message": "Resource not found"}
**原因**:
1. URL/端点错误
2. 资源已删除
3. ID 不存在
4. 尾部斜杠问题
**诊断**:
bash
# 检查 URL 是否正确
curl -I https://api.example.com/users/123
# 尝试带/不带尾部斜杠
curl https://api.example.com/users/
curl https://api.example.com/users
**解决方案**:
javascript
// 优雅地处理 404
c