在 HTTP 通信中,Content-Type 是最重要、也最容易被忽略的一个请求 / 响应头。
它直接决定了:
- 浏览器如何解析数据
- 后端如何读取请求体
- 前后端能否正确“对话”
一、Content-Type 是什么?
Content-Type 是 HTTP 头字段,用来声明:
👉 消息体(Body)的数据类型与格式
示例:
Content-Type: application/json
意思是:
这是一段 JSON 格式的数据
二、Content-Type 的作用(核心)
1️⃣ 告诉接收方如何解析数据
- 浏览器 → 解析响应内容
- 后端 → 解析请求体
2️⃣ 决定前后端数据交互方式
不同 Content-Type → 不同解析逻辑:
- JSON
- 表单
- 文件
- 二进制流
3️⃣ 影响浏览器行为
- 是否直接显示
- 是否下载
- 是否触发文件保存
三、Content-Type 的基本格式
Content-Type: type/subtype; parameter=value
示例:
Content-Type: text/html; charset=UTF-8
含义:
- 主类型:
text - 子类型:
html - 参数:
charset=UTF-8
四、常见 Content-Type 类型分类
1️⃣ text 类型
| 类型 | 说明 |
|---|---|
| text/plain | 纯文本 |
| text/html | HTML 页面 |
| text/css | CSS 样式 |
| text/javascript | JS(已过时,推荐 application/javascript) |
2️⃣ application 类型(最常用)
JSON(前后端主流)
Content-Type: application/json
前端:
fetch("/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Tom" })
});
后端(示意):
- Spring Boot:
@RequestBody - Node.js:
body-parser
表单(传统方式)
Content-Type: application/x-www-form-urlencoded
格式:
name=Tom&age=20
文件上传(重点)
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
特点:
- 支持文件 + 普通字段
- 必须带 boundary
HTML 示例:
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
</form>
3️⃣ image 类型
| 类型 | 说明 |
|---|---|
| image/png | PNG 图片 |
| image/jpeg | JPG 图片 |
| image/gif | GIF 图片 |
| image/svg+xml | SVG |
4️⃣ audio / video 类型
audio/mpeg
video/mp4
5️⃣ application/octet-stream(下载)
Content-Type: application/octet-stream
表示:
- 任意二进制流
- 浏览器通常会下载文件
五、请求 Content-Type vs 响应 Content-Type
请求头(前端 → 后端)
POST /api/login
Content-Type: application/json
👉 告诉服务器:
“我发的是 JSON”
响应头(后端 → 前端)
HTTP/1.1 200 OK
Content-Type: application/json
👉 告诉浏览器:
“我返回的是 JSON”
六、Content-Type 与 Accept 的区别
| 对比 | Content-Type | Accept |
|---|---|---|
| 表示 | 实际发送的数据类型 | 期望接收的数据类型 |
| 使用方 | 发送方 | 接收方 |
| 常见位置 | 请求 / 响应 | 请求 |
示例:
Accept: application/json
Content-Type: application/json
七、常见错误与坑位
❌ 1. Content-Type 写错,后端收不到数据
body: { name: "Tom" } // 错误
必须:
body: JSON.stringify({ name: "Tom" })
❌ 2. 上传文件手动设置 multipart
headers: {
"Content-Type": "multipart/form-data" // 错误
}
❌ 会丢失 boundary
✅ 让浏览器自动设置
❌ 3. 编码问题导致中文乱码
Content-Type: text/html
应加:
Content-Type: text/html; charset=UTF-8
八、常见后端框架对 Content-Type 的要求
| 后端 | 说明 |
|---|---|
| Spring Boot | JSON 需 @RequestBody |
| Express | 需 body-parser |
| Django | request.body |
| PHP | $_POST / php://input |
九、Content-Type 速查表(实用)
| 场景 | Content-Type |
|---|---|
| JSON 接口 | application/json |
| 普通表单 | application/x-www-form-urlencoded |
| 文件上传 | multipart/form-data |
| HTML 页面 | text/html |
| 文件下载 | application/octet-stream |
十、总结一句话
✔ Content-Type 决定数据如何被解析
✔ 前后端交互是否成功,80% 看它
✔ JSON 是现代接口主流
✔ 文件上传别手动设置 Content-Type
发表回复