Content-Type

Content-Type(MediaType),即是Internet Media Type,互联网媒体类型,也叫做MIME类型。在互联网中有成百上千种不同的数据类型,HTTP在传输数据对象时会为他们打上称为MIME的数据格式标签,用于区分数据类型。最初MIME是用于电子邮件系统的,后来HTTP也采用了这一方案。

HTTP协议消息头中,使用Content-Type来表示请求和响应中的媒体类型信息。它用来告诉服务端如何处理请求的数据,以及告诉客户端(一般是浏览器)如何解析响应的数据,比如显示图片,解析并展示html等等。

Content-Type的格式:


Content-Type:type/subtype;parameter


1. type:主类型,任意的字符串,如text,如果是*号代表所有;
2. subtype:子类型,任意的字符串,如html,如果是*号代表所有,用“/”与主类型隔开;
3. parameter:可选参数,如charset,boundary等。

例如:


Content-Type: text/html;
Content-Type: application/json;charset:utf-8;

1. application/x-www-form-urlencoded

提交的数据需要按照 key1=val1&key2=val2 的方式进行编码,keyval 都进行了 URL 转码,一般用于表单提交

1.1 参数加在url后面

如使用 axios 发送 POST 请求:


  const axiosInstance = axios.create({
    baseURL: 'https://api.**.com'
  })

  return axiosInstance.post(
    '/manager/auth', // url
    '', // 若配置了这部分,参数会写在请求体中
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      params: {
        regionName: '陕西省',
        regionCode: '610000'
      } // 这部分参数会加在url后面,需要使用params作为key
    } 
  )

 x-www-form-urlencoded-url
 x-www-form-urlencoded

1.2 参数写在 请求体 里的 formData 形式


  import qs from 'qs'

  let data = qs.stringify({
    regionName: '陕西省',
    regionCode: '610000'
  })

  return axiosInstance.post(
    '/manager/auth',
    data,
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
  )

 url
 body

2. application/json

json是我们比较常用的数据格式,以键值对的形式
如使用 axios 发送 POST 请求:


 return axiosInstance.post(
    '/manager/auth',
    {
      regionName: '陕西省',
      regionCode: '610000'
    },
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
 )

 json

3. multipart/form-data

一般使用表单上传文件时,使用这个

如使用 axios 发送 POST 请求:


  let formData = new FormData()
  formData.append('regionName', '陕西省')
  formData.append('regionCode', '610000')
  formData.append('file', new Blob())

  return axiosInstance.post('/manager/auth', formData,
   {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )

 formData

4. application/octet-stream

下载文件


return axiosInstance.get('/file/id/download', '',
   {
      responseType: "blob",
      headers: {
        'Content-Type': 'application/octet-stream;charset=UTF-8'
      }
   }
)

5. text/plain

text文本字符串

6. text/xml

XML-RPC(XML Remote Procedure Call)。它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范


参考文章

Content-Type 详解--简书

Last modification:December 1st, 2022 at 10:54 am
如果觉得我的文章对你有用,请随意赞赏或留下你的评论~