axios基本用法

179 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第六天,点击查看活动详情这篇文章不谈axios的复杂使用 先给大家整明白最基础的axios用法 能够清楚axios传参与不传参都怎么写

axios的请求方法:get、post、put、patch、delete

  • get:一般用于获取数据

  • post:一般用于表单提交与文件上传

  • patch:更新数据(只将修改的数据推送到后端)

  • put:更新数据(所有数据推送到服务端)

  • delete:删除数据

    备注:post一般用于新建数据,put一般用于更新数据,patch一般用于数据量较大的时候的数据更新。

get请求

完整写法(传入一个完整的对象)

axios({
    url:'http://localhost:9999/student/getAllStudent',
    method:'get'
    })
    .then(res=>{
    console.log(res);})   //无参请求
 axios({
     url:'http://localhost:9999/student/getAllStudent'
     })
     .then(res=>{
         console.log(res);})    //不写method ,默认是get请求
     .catch(error=>{
         console.log(error);
         })

axios({
     url:'http://localhost:9999/student/getAllStudent?id=1',
     method:'get'})
     .then(res=>
     console.log(res);)   //有参请求 参数拼接到URL中
     .catch(error=>{
         console.log(error);
         })
axios({
     url:'http://localhost:9999/student/getAllStudent?id=1',
     method:'get',
     params:{    //有参请求 参数放到params中传递
     id:1 }
     })
     .then(res=>{
     console.log(res);
     })
     .catch(error=>{
         console.log(error);
         })

简写

axios.get('/data.json')  //不传参
    .then(res=>{
    console.log(res);
    })
    .catch(err=>
    console.log(err);
    });
axios.get('/data.json',{
    params:{  //记住这种传参方式
    id:1
    }
    })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})
axios.get('/data.json?id=1')
    .then(res=>{     //参数拼接到URL中
    console.log(res)})
    .catch(err=>{
    console.log(err)})

post请求(与put请求写法相似)

完整写法

axios({
    method:'post',
    url:'/user',
    data:{               //data参数中进行传参
        name:'ff',
        qq:'222222222'
        }
    })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})

简写

axios.post('/user',{   //传参
     name:'ff',
     qq:'222222222'
     })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})

其中 传递的参数可以有两种格式:form-data(图片上传,文件上传) 和 applicition/json(目前比较流行)

上面两种方法 都是 appliction/json格式  

let formData = new FormData()
let data = {
    id:1
    }
for (let key in data){
    formData.append(key,data[key])  //创建form-data格式数据
  }
  
 axios({
     method:'post',
     url:'/user',
     data:formData
     })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})

该请求发出之后可以在浏览器中查看此次请求的request header里面content-type: 为 form-data形式

delete请求(写法参考get)

完整写法

axios({
    method:'delete',
    url:'/user',
    data:{
    id:1
    }
    })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})

简写

axios.delete('/user',{
     params:{             //记住这种传参方式
    id:1
    }
      })
    .then(res=>{
    console.log(res);})
    .catch(err=>{
    console.log(err)})

当然也可以直接在URL中拼接参数