HTTP请求与跨域配置知识

6 阅读2分钟
  1. HTTP请求结构
  2. 跨域配置原理
  3. CORS响应头详解
  4. 前后端配置示例
  5. 特殊场景处理
  6. 安全注意事项

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/HEADGET /data
复杂请求含自定义头或特殊方法PUT /data + X-Custom-Header

2. 跨域配置原理

2.1 同源策略限制

// 前端不同源请求示例
fetch('https://api.example.com/data') // 当前页为 https://your-site.com
  .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发送跨域请求
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 安全配置检查表

  • 生产环境禁用*通配符
  • 限制允许的HTTP方法
  • 定期审计CORS配置
  • 使用HTTPS加密传输