Axios请求与content-type设置

2,026 阅读1分钟

对于前端请求,什么时候需要设置 content-type

get请求不存在设置content-type。只有post和put用到content-type,常用的post方式,所以这里着重说post。

常用的 content-type 类型有哪些 ?

post的content-type三种类型:

  • Content-Type: application/json
    对于axios,post的时候axios.post(url,{a:1,b:2}),第二个参数是对象的时候,默认是这个类型。
  • Content-Type: application/x-www-form-urlencoded
    对于axios,post的时候let data = {a:1,b:2}; axios.post(url,qs.stringify({ data })),第二个参数是字符串的时候,默认是这个类型
  • Content-Type: multipart/form-data
    对于axios,post的时候let data = new FormData(); data.append('a',1'); data.append('b',2); axios.post(url,data),参数是formData类型的时候,默认是这个类型,如果用form自带的action提交,默认是这个类型

以上三种方式,服务器会以不同的方式解析,这点尤其注意!!!

需要注意的是:

axios中post请求 content-type默认值 和 原生的AJAX中post请求 content-type默认值不一样,和其他请求库(例如:isomorphic-fetch)的默认值也不一样。 这些需要具体区分一下。

针对 axios 库:

content-type会根据参数的类型会自动有对应的值,一般无需设置。
但是,有些情况是,我想传对象,但实际服务器需要的的是application/x-www-form-urlencoded,此时需要只需要统一设置请求前将参数变成字符串即可transformRequest: [ function (data) { return Qs.stringify(data) } ]。

Postman 工具中的格式选择

以使用 axios 库为例:

  • Content-Type: application/json 时,选择 body / raw / json
  • Content-Type: application/x-www-form-urlencoded 时,选择 body / x-www-form-urlencoded
  • Content-Type: multipart/form-data 时,选择 body / form-data