axios配置请求头content-type

Table of Contents
  • axios 是Ajax的一个插件,axios虽然是一个插件,但是我们不需要通过Vue.use(axios)来使用,下载完成后,只需在项目中引入即可。(一般我们放在了请求接口的公共文件中引用)

    npm install axios -S

    • 1
  • axios 发送post请求时默认是直接把 json 放到请求体中提交到后端的,axios默认的请求头content- type类型是’application/json;charset=utf-8’.

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

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

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • Content-Type: application/json这种参数是默认的就不说了

  • 若后端需要接受的数据类型为:application/x-www-form-urlencoded,我们前端该如何配置:
    1 用 URLSearchParams 传递参数

    var param = new URLSearchParams() param.append('name',name) param.append('age' , age) axios( { method:'post', url: url, data : param, } ).then(res => res).catch(err => err)

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

2 配置axios请求头中的content-type为指定类型(这个比较常用)

axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";


  * 1

3 引入 qs ,这个库是 axios 里面包含的,不需要再下载了

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)
})


  * 1
  * 2
  * 3
  * 4
  * 5
  * 6
  * 7
  * 8
  * 9
  * 10
  * 11
  * 12
  * 13
  * 14

* 若后端需要接受的数据类型为:Content-Type: multipart/form-data,我们前端该如何配置:
应用场景:对于这种类型的数据,我们常见前端页面上传个人图像,然后点击保存发送后端修改原始数据

let params = new FormData()
params.append('file', this.file)
params.append('qq', this.qq)
params.append('weChat', this.WeChat)
axios.post(URL, params, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
          if (res.data.code === 0) {
                this.$router.go(-1)
          }
        }).catch(error => {
          alert('更新用户数据失败' + error)
        })


  * 1
  * 2
  * 3
  * 4
  * 5
  * 6
  * 7
  * 8
  * 9
  * 10
  * 11

0 评论

发表评论

精品游戏◆乐于分享


Title