- HTTP请求结构
- 跨域配置原理
- CORS响应头详解
- 前后端配置示例
- 特殊场景处理
- 安全注意事项
1. HTTP请求结构
1.1 请求组成
POST /api/login HTTP/1.1
Host: example.com
Content-Type: application/json
{"username": "user", "password": "pass"}
- 请求行:
方法 URI 协议版本
- 请求头: 键值对元数据
- 空行: 分隔头部与主体
- 请求体: 数据载体
1.2 请求类型对比
类型 | 特点 | 示例 |
---|
简单请求 | 无自定义头,GET/POST/HEAD | GET /data |
复杂请求 | 含自定义头或特殊方法 | PUT /data + X-Custom-Header |
2. 跨域配置原理
2.1 同源策略限制
fetch('https://api.example.com/data')
.then(...)
2.2 CORS工作机制
graph TD
A[浏览器发送请求] --> B{是否跨域?}
B -->|是| C[添加Origin头]
C --> D[服务器返回CORS头]
D --> E{是否允许?}
E -->|是| F[处理响应]
E -->|否| G[拦截响应]
3. CORS响应头详解
3.1 核心响应头
add_header Access-Control-Allow-Origin 'https://your-frontend.com';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
add_header Access-Control-Allow-Credentials 'true';
3.2 头字段说明
响应头 | 作用 | 示例值 |
---|
Access-Control-Allow-Origin | 允许的源 | https://your-site.com |
Access-Control-Expose-Headers | 暴露自定义头 | X-Custom-Header |
Access-Control-Max-Age | 预检缓存时间 | 3600 |
4. 前后端配置示例
4.1 前端配置
fetch('https://api.example.com/data', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify({ key: 'value' })
});
4.2 后端配置示例
Node.js (Express):
app.use(cors({
origin: 'https://your-frontend.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type'],
credentials: true
}));
Nginx配置:
location /api/ {
add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
if ($request_method = OPTIONS) {
return 204;
}
}
5. 特殊场景处理
5.1 SSE长连接跨域
const eventSource = new EventSource('https://api.example.com/stream', {
withCredentials: true
});
Content-Type: text/event-stream
5.2 文件上传跨域
<form action="https://api.example.com/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
</form>
Access-Control-Allow-Headers: Content-Type, Content-Disposition
6. 安全注意事项
6.1 配置风险矩阵
危险配置 | 风险 | 正确做法 |
---|
Access-Control-Allow-Origin: * + 凭证 | Cookie泄露 | 明确指定源 |
暴露过多响应头 | 信息泄露 | 按需设置Expose-Headers |
不验证Origin头 | CSRF攻击 | 服务端校验Origin |
6.2 安全配置检查表