HTTP 中的 Content-Type

Content-Type 指定 Body 的媒体资源类型,如果是请求头,则代表请求体的资源类型,如果是响应头,则代表响应体的资源类型。

资源类型通过 MIME(Multipurpose Internet Mail Extensions )进行表示,以此为基础的 npm 库 mime-db 也常用在各个 Node.js 服务器框架。

常见的文件拓展名与 MIME Type 可见 MIME Types

请求头中的 Content-Type

当请求头中含有 Content-Type 时,它指明 Request Body 的媒体资源类型,此时一般为 POST 请求。

当前端向后端请求 API 接口时,请求体一般为 JSON 数据类型,此时需要配置 Content-Type: application/json

除此之外,在 API 中常见以下几种请求头中的 Content-Type:

  • aplication/json:请求体为 JSON
  • application/x-www-form-urlencoded:请求体为以 & 分割的字符串,如 a=3&b=4
  • multipart/form-data:请求体以 Boundary 分割

响应头中的 Content-Type

当响应头中含有 Content-Type 时,它指明 Response Body 的媒体资源类型。

因为我们可以通过 HTTP 去请求各种各样的资源,因此 Content-Type 基本上可以是所有 MIME 类型。

而在前端中,涉及到的响应头中的 Content-Type 为以下几种:

  • text/html
  • text/css
  • application/javascript
  • image/png
  • image/jpeg
  • image/webp
  • image/svg+xml

实例

我在 Apifox 中演示了知名网站关于强缓存与协商缓存的应用。见文档

作业

  1. 你接触过哪些 MIME Type
  2. 你在 HTTP Header 中见过那些 Content-Type

猜你喜欢

转载自juejin.im/post/7139529540832854029