axios 请求头content-type

content-type的三种常见数据格式:

 1 默认的格式请求体中的数据会以json字符串的形式发送到后端
  'Content-Type: application/json '
 2 请求体中的数据会以普通表单形式(键值对)发送到后端
  'Content-Type: application/x-www-form-urlencoded'
 3 它会将请求体的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件
  'Content-Type: multipart/form-data'

Content-Type: application/json这种参数是默认的 提交json 格式的数据

若后端需要接受的数据类型为:application/x-www-form-urlencoded
content-type :application / x-www-form-urlencoded 要求的参数格式是键值对拼接的方式:key=value&key=value
1 用 URLSearchParams 传递参数
var param = new URLSearchParams()
  param.append('name',name)
  param.append('age' , age)
  console.log(param.toString())
axios(
	{
	  method:'post',
	  url: url,
	  data : param,
	}
	).then(res => {})

2 配置axios请求头中的content-type为指定类型
axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";
或者引入qs, 
import Qs from 'qs'
let params= {
    "name": "ll",
    "age": "18"
}

axios({
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'post',
    url: url,
    data: Qs.stringify(params)
})
若后端需要接受的数据类型为:Content-Type: multipart/form-data
常用与上传文件
let params = new FormData()
params.append('file', xx)
params.append('qq', xxx)
params.append('weChat',xxx)
axios.post(URL, params, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {})
posted @ 2022-10-27 13:51  7c89  阅读(183)  评论(0编辑  收藏  举报