美文网首页vue-进阶
Vue使用axios,设置axios请求格式为form-data

Vue使用axios,设置axios请求格式为form-data

作者: iimT | 来源:发表于2018-03-31 16:14 被阅读5217次

    Cover

    Cover

    在Vue中使用axios

    这个老生常谈了,还是先记录一遍,方面后面自己查。

    !!! 设置form-data请求格式直接翻到后面看。

    1. 安装axios

    在项目下执行npm install axios
    之后在main.js中,添加:

    import axios from 'axios' //引入
    
    //Vue.use(axios) axios不能用use 只能修改原型链 
    Vue.prototype.$axios = axios
    

    2. 发送GET请求

    axios封装了get方法,传入请求地址和请求参数,就可以了,同样支持Promise。

    //不带参数的get请求
    
    let url = "..."
    this.$axios.get(url)
    .then((res) => {
        console.log(res) //返回的数据
    })
    .catch((err) => {
        console.log(err) //错误信息
    })
    

    不过它的参数需要写在params属性下,也就是:

    //带参数的get请求
    
    let url = "...getById"
    this.$axios.get(url, {
        params: {
            id: 1
        }
    })
    .then((res) => {
        console.log(res) //返回的数据
    })
    .catch((err) => {
        console.log(err) //错误信息
    })
    

    2. 发送post请求

    与上面相同,就是参数不需要写在params属性下了,即:

    //带参数的post请求
    
    let url = "...getById"
    let data = {
        id: 1
    }
    
    this.$axios.post(url, data)
    .then((res) => {
        console.log(res) //返回的数据
    })
    .catch((err) => {
        console.log(err) //错误信息
    })
    

    3. 经典写法

    axios也可以用jQ的写法,不过回调函数还是Promise的写法,如:

    this.$axios({
      method: 'post',
      url: '...',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    }).then((res) => {
        console.log(res)
    })
    

    设置form-data请求格式

    我用默认的post方法发送数据的时候发现后端获取不到数据,然而在network中看到参数是的确传出去的了。而且用postman测试的时候也是可以的,比较了下两个的不同发现是postman使用的是form-data格式,于是用form-data格式再次请求,发现OJBK

    在查找设置请求格式的时候花了点时间,网上的方案有好几个,这个我亲测成功,发上来。

    import axios from "axios"  //引入
    
    //设置axios为form-data
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.transformRequest = [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
    }]
    
    
    //然后再修改原型链
    Vue.prototype.$axios = axios
    
    

    写在最后

    我是iimT, 一个固执的技术直男。

    我的微博 : @_iimT

    我的微信公众号 : iimT   个人博客: www.iimt.me

    相关文章

      网友评论

        本文标题:Vue使用axios,设置axios请求格式为form-data

        本文链接:https://www.haomeiwen.com/subject/qbogcftx.html