vue中axios的参数位置整理

每次在进行前后端联调的时候,总是因为参数放不对而影响进度,我人都麻了,真的记不住,还是整理一下以便后续开发

一、vue2和vue3的接口请求头

// vue 2
const res = await this.$axios.get(``,{})

// vue 3
const { proxy } = getCurrentInstance()
const res = await proxy.$axios.get(``,{})

主要区别就是this不能用了

二、不同请求类型

我目前所接触到的就是GET, POST, PUT, DELETE, 其中get,post最多,其他的以后再增加,

GET请求 

一般用于从后端获取数据,参数位置一般为path或query

const { proxy } = getCurrentInstance()

const onLogin = () => {
    const iccid = '11111'
    try{
        const res = await proxy.$axios.get(`/userInfo/${iccid}`)
    }catch(e){
     proxy.$message.error(e.message)
    }
}


 如果传参位置在路径里面,就直接写在路径里

 对于放在query的参数,需要在路径后面,用params传递

const { proxy } = getCurrentInstance()

const onLogin = () => {
    const userId= 1
    try{
        const res = await proxy.$axios.get(`/userInfo`,{
            params:{
                userId            
            }
        }
        )
    }catch(e){
     proxy.$message.error(e.message)
    }
}

POST请求

传参一般有path,query,body三种形式,path跟get一致,

之前query传参写错了,与get不同,要放在第三个括号里,并且要用params包裹起来

const { proxy } = getCurrentInstance()

const onLogin = () => {
    const endTime = '2021/12/6'
    const iccid = '1111111'
    try{
        const res = await proxy.$axios.post(`/userInfo`,{},
        {
            params:{
                endTime,
                iccid            
            }
        })
    }catch(e){
     proxy.$message.error(e.message)
    }
}

 query同样也是放进param里面

const { proxy } = getCurrentInstance()

const onLogin = () => {
    const name = '糯米w'
    const phone = '1111111'
    try{
        const res = await proxy.$axios.post(`agents`, {
              name,
              phone,
            })
        )
    }catch(e){
     proxy.$message.error(e.message)
    }
}

如果参数是放在body里面,就不需要params,而是直接放参数就好

三、特殊处理的接口

上面提到的都是封装好的接口,有时候必须要使用原装接口,最常用的就是图片,文件的传输

这是一个文件传输的接口,因此出现了formData这种数据格式

 var Data = new FormData()
 Data.append('file', cardMessage.uploadMsg)
const res = await proxy.$axios({
              url: `Transfer`,
              method: 'POST',
              data: Data,
              headers: {
                'Content-Type': 'multipart/form-data',
              },
              params: {
                type: 'BACK',
              }
            })

对于数据必须用FormData处理,是为了将数据编译成键值对

 然后将其放在data里面被接收

然后对于其他的参数,放在params里面,这其实就是用到axios默认的请求配置项

我先回去把axios好好学习一下,然后再把其他文件类型也写出来

猜你喜欢

转载自blog.csdn.net/qq_41443611/article/details/121742819