HTTP 常用标头总结

24 天前(已编辑)
2

HTTP 常用标头总结

一、请求标头 (前端发送)

Accept

作用: 告诉服务器客户端能处理什么格式

常用值:

  • application/json
    • API 请求
  • text/html
    • 页面请求
  • image/webp, image/png
    • 图片格式偏好
  • */*
    • 任意格式

实战:

// fetch 自动携带 Accept: */*
// 明确指定
fetch('/api/data', {
  headers: { 'Accept': 'application/json' }
})

Accept-Encoding

作用: 告诉服务器我能接受的压缩格式,服务器据此返回压缩响应节省带宽

常用值: gzip, deflate, br

实战:

// 浏览器自动携带
// 请求: Accept-Encoding: gzip, deflate, br
// 响应: Content-Encoding: br (Brotli压缩,压缩率最高)

Accept-Language

作用: 声明偏好的语言版本

实战:

// 服务器据此返回对应语言
// Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
// 多语言网站根据此标头返回正确内容

Authorization

作用: 携带认证令牌,最常用的身份验证方式

常用格式:

// Bearer Token (最常用)
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...'

// Basic 认证
'Authorization': 'Basic ' + btoa('user:pass')

// 封装示例
const api = {
  get(url) {
    return fetch(url, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
  }
}

Content-Type

作用: 告诉服务器发送的数据格式(POST/PUT 请求)

常用值:

  • application/json
    • JSON 数据
  • application/x-www-form-urlencoded
    • 表单数据
  • multipart/form-data
    • 文件上传
  • text/plain
    • 纯文本

实战:

// JSON 请求(最常用)
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'John' })
})

// 文件上传(自动设置 multipart/form-data)
const formData = new FormData()
formData.append('file', fileInput.files[0])
fetch('/api/upload', { method: 'POST', body: formData })

Cookie

作用: 自动携带该域名下已存储的 Cookie

实战:

// 浏览器自动随请求发送(同源)
// HttpOnly Cookie 无法通过 JS 读取(更安全)
// 服务端设置
// Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict

Host

作用: 请求的目标域名(虚拟主机识别)

实战:

// 同一服务器托管多个网站时靠它区分
// fetch 自动设置
// Host: api.example.com

Origin

作用: 请求来源(协议+域名+端口),CORS 请求自动发送

实战:

// CORS 预检请求和实际请求都会携带
// Origin: https://myapp.com
// 服务器据此判断是否允许跨域

Referer

作用: 当前请求来自哪个页面(来源追踪、防盗链)

实战:

// 统计来源
console.log(document.referrer) // 'https://example.com/page'

// 配合 Referrer-Policy 控制发送粒度
// <meta name="referrer" content="strict-origin-when-cross-origin">

User-Agent

作用: 客户端标识(浏览器、操作系统信息)

实战:

// 浏览器自动设置
// User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)...
// 可用于简单设备检测,但推荐用特性检测
if ('serviceWorker' in navigator) { /* 支持 SW */ }

二、响应标头 (服务端返回)

Content-Type

作用: 告诉浏览器返回的数据类型,决定如何处理

常用值:

  • text/html
    • 渲染页面
  • application/json
    • JSON 数据
  • application/javascript
    • JavaScript
  • text/css
    • 样式表
  • image/png
    • 图片

重要: 错误设置会导致浏览器拒绝执行(如 JS 文件返回 text/html)

// 常见错误
res.setHeader('Content-Type', 'text/html') // 但返回的是 JSON
// 正确
res.setHeader('Content-Type', 'application/json')
res.json({ error: 'Not Found' })

Content-Encoding

作用: 响应体使用的压缩格式

实战:

// 请求: Accept-Encoding: gzip, deflate, br
// 响应: Content-Encoding: br
// 浏览器自动解压缩,无需 JS 处理

// 服务端启用压缩(Express)
const compression = require('compression')
app.use(compression())

作用: 服务端向客户端写入 Cookie

关键参数:

// 基础用法
res.setHeader('Set-Cookie', 'token=abc123; Path=/')

// 安全配置(生产环境必选)
res.setHeader('Set-Cookie', [
  // HttpOnly: JS 无法读取,防止 XSS 盗取
  'token=abc123; HttpOnly; Secure; SameSite=Strict; Path=/',

  // 过期时间
  'theme=dark; Max-Age=31536000; Path=/',

  // 跨域 Cookie(需要配合 CORS)
  'tracking=xyz; SameSite=None; Secure; Path=/'
])

// SameSite 取值
// Strict: 完全阻止跨域发送(最安全)
// Lax: 允许部分导航(推荐默认值)
// None: 允许跨域,但必须 Secure(HTTPS)

Cache-Control

作用: 缓存控制指令,最重要的缓存header

常用值: | 值 | 含义 | |---|------| | max-age=3600 | 缓存有效期(秒) | | public | CDN/浏览器都可缓存 | | private | 仅浏览器缓存 | | no-cache | 需协商验证 | | no-store | 完全不缓存 | | must-revalidate | 过期后必须重新验证 |

实战:

// 静态资源(长期缓存,文件名哈希)
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')

// HTML(不缓存或短期)
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')

// API 数据
res.setHeader('Cache-Control', 'private, max-age=60')

// 配合 ETag 实现协商缓存

ETag / If-None-Match

作用: 资源版本标识,用于协商缓存

实战:

// 首次请求
// 响应: ETag: "abc123"
// 浏览器缓存 ETag

// 再次请求(浏览器自动)
// 请求: If-None-Match: "abc123"
// 响应: 304 Not Modified(不返回body,节省带宽)
// 或: 200 OK + 新内容(ETag 变化时)

Last-Modified / If-Modified-Since

作用: 资源最后修改时间,另一种协商缓存方式

实战:

// 响应: Last-Modified: Wed, 21 Oct 2025 07:28:00 GMT
// 下次请求: If-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT
// 服务器判断是否返回 304

// 通常 ETag 优先级更高(更精确)

Vary

作用: 告诉缓存哪些请求头影响响应,缓存多版本

实战:

// 缓存多个语言版本
res.setHeader('Vary', 'Accept-Language')
// 缓存多个压缩版本
res.setHeader('Vary', 'Accept-Encoding')
// 组合
res.setHeader('Vary', 'Accept-Encoding, Accept-Language')

Location

作用: 重定向目标地址,或创建资源的URI

实战:

// 3xx 重定向
res.setHeader('Location', '/new-page')
res.statusCode = 302

// 201 Created
res.statusCode = 201
res.setHeader('Location', '/users/123')

三、安全标头 (防护必备)

Content-Security-Policy (CSP)

作用: 限制资源加载来源,防止 XSS 和数据注入

常用指令:

// 基础配置
"default-src 'self'"  // 默认仅同源

// 常见配置组合
"default-src 'self'; script-src 'self' https://cdn.example.com; img-src *; style-src 'self' 'unsafe-inline'"

// 详细说明
// script-src: 可执行的 JS 来源
// img-src: 图片来源
// style-src: 样式来源
// connect-src: AJAX/WebSocket 目标
// frame-ancestors: 可嵌入的来源(替代 X-Frame-Options)

实战:

// 响应头设置(推荐)
res.setHeader('Content-Security-Policy', "default-src 'self'")

// 或 HTML meta(不支持 report-uri)
// <meta http-equiv="Content-Security-Policy" content="default-src 'self'">

// 违规报告
res.setHeader('Content-Security-Policy-Report-Only',
  "default-src 'self'; report-uri /csp-report")

Strict-Transport-Security (HSTS)

作用: 强制使用 HTTPS,抵御中间人攻击

实战:

// 基础
res.setHeader('Strict-Transport-Security', 'max-age=31536000')

// 完整配置
res.setHeader('Strict-Transport-Security',
  'max-age=31536000; includeSubDomains; preload')

// 效果:首次访问后,浏览器记住 1 年内必须用 HTTPS
// 防止 HTTP 降级攻击

X-Content-Type-Options

作用: 防止浏览器 MIME 嗅探,强制按声明的类型处理

实战:

// 必需设置!
res.setHeader('X-Content-Type-Options', 'nosniff')

// 效果:即使文件内容像 JS,但声明是 text/html,也不会执行
// 防止资源类型伪装攻击

X-Frame-Options

作用: 防止被 iframe 嵌入,避免点击劫持

实战:

// 完全禁止嵌入
res.setHeader('X-Frame-Options', 'DENY')

// 仅允许同源嵌入
res.setHeader('X-Frame-Options', 'SAMEORIGIN')

// 现代推荐:使用 CSP 替代
// Content-Security-Policy: frame-ancestors 'none'

四、CORS 标头 (跨域必备)

基础概念

CORS 需要服务端配合设置,前端只需普通 fetch:

// 前端(无特殊处理)
fetch('https://api.example.com/data', { mode: 'cors' })

// 简单请求:浏览器直接发送,服务器设置 Access-Control-Allow-Origin
// 复杂请求:先发 OPTIONS 预检,服务器确认后才发真实请求

Access-Control-Allow-Origin

作用: 允许跨域访问的来源

实战:

// 允许特定域名(推荐)
res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com')

// 允许任意来源(不能配合 credentials)
res.setHeader('Access-Control-Allow-Origin', '*')

// 动态设置
const origin = req.headers.origin
if (allowedOrigins.includes(origin)) {
  res.setHeader('Access-Control-Allow-Origin', origin)
}

Access-Control-Allow-Methods

作用: 允许的 HTTP 方法

实战:

res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')

Access-Control-Allow-Headers

作用: 允许携带的请求头

实战:

res.setHeader('Access-Control-Allow-Headers',
  'Content-Type, Authorization, X-Custom-Token')

Access-Control-Allow-Credentials

作用: 是否允许发送 Cookie

实战:

// 前端
fetch('https://api.example.com', { credentials: 'include' })

// 服务端(必须配合具体-origin,不能是 *)
res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com')
res.setHeader('Access-Control-Allow-Credentials', 'true')

Access-Control-Max-Age

作用: 预检结果缓存时间,减少 OPTIONS 请求

实战:

// 缓存 1 小时
res.setHeader('Access-Control-Max-Age', '3600')

Access-Control-Expose-Headers

作用: 暴露给 JS 读取的响应头

实战:

// 前端读取
fetch('/api/data').then(res => {
  res.headers.get('X-Total-Count') // undefined 除非暴露
})

// 服务端
res.setHeader('Access-Control-Expose-Headers', 'X-Total-Count, X-Request-Id')

五、性能优化标头

作用: 预加载/预连接资源

实战:

// 预加载关键资源
res.setHeader('Link',
  '</styles.css>; rel=preload; as=style, </main.js>; rel=preload; as=script')

// HTML 中使用(更常见)
// <link rel="preload" href="/main.js" as="script">
// <link rel="preconnect" href="https://fonts.googleapis.com">
// <link rel="dns-prefetch" href="https://cdn.example.com">

Server-Timing

作用: 服务端性能指标

实战:

// 服务端埋点
res.setHeader('Server-Timing', 'db;dur=50, api;dur=120.5')

// 前端读取
const entries = performance.getEntriesByType('resource')
entries.forEach(e => console.log(e.serverTiming))

Accept-Ranges / Range

作用: 断点续传、大文件分片下载

实战:

// 服务端声明支持
res.setHeader('Accept-Ranges', 'bytes')

// 客户端请求部分内容
const xhr = new XMLHttpRequest()
xhr.setRequestHeader('Range', 'bytes=0-1023') // 前1KB

// 响应
// 206 Partial Content
// Content-Range: bytes 0-1023/14688
// Content-Length: 1024

六、调试用标头

X-Request-Id / X-Correlation-Id

作用: 请求追踪 ID,串联日志排查问题

实战:

// 服务端生成并返回
const requestId = crypto.randomUUID()
res.setHeader('X-Request-Id', requestId)
console.log({ requestId, message: 'Error', ... })

// 前端捕获
fetch('/api/data').catch(err => {
  const requestId = err.response?.headers.get('X-Request-Id')
  console.error('Request ID:', requestId) // 发给服务器排查
})

七、速查表

开发常用组合

// API 响应
{
  'Content-Type': 'application/json',
  'Cache-Control': 'private, max-age=60',
  'Access-Control-Allow-Origin': 'https://myapp.com'
}

// 静态资源
{
  'Content-Type': 'application/javascript', // 或对应类型
  'Cache-Control': 'public, max-age=31536000, immutable',
  'Content-Encoding': 'br' // 启用压缩
}

// HTML 页面
{
  'Content-Type': 'text/html; charset=utf-8',
  'Cache-Control': 'no-cache',
  'Content-Security-Policy': "default-src 'self'",
  'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
}

安全头检查清单

☑ Content-Security-Policy
☑ Strict-Transport-Security
☑ X-Content-Type-Options: nosniff
☑ X-Frame-Options: DENY (或 CSP frame-ancestors)
☑ Set-Cookie: HttpOnly; Secure; SameSite=Strict
☑ 隐藏 X-Powered-By

常见问题

1. 为什么 fetch 返回 JSON 但无法读取?

// 检查 Content-Type 是否正确
res.setHeader('Content-Type', 'application/json')

2. 为什么 Cookie 没生效?

// 检查 SameSite 设置
// Chrome 默认 Lax,跨域需要 SameSite=None; Secure

3. 为什么缓存没生效?

// 检查 Vary 是否包含变化的请求头
res.setHeader('Vary', 'Accept-Encoding')
// 检查是否有 no-store

总结

核心标头就这些:

类别必备标头
请求Authorization, Content-Type, Cookie
响应Content-Type, Cache-Control, Set-Cookie
安全CSP, HSTS, X-Content-Type-Options
跨域Access-Control-Allow-Origin, Credentials 系列
缓存ETag, Last-Modified, Vary

参考: MDN HTTP Headers

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...