前端入门5:Axios

发布于 27 天前 3 次阅读 365 字 预计阅读时间: 2 分钟 前端


入门

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    //发送GET请求
    document.querySelector('#btnGet').addEventListener('click', () => {
        axios({
        method:'GET',
        url:'https://mock.apifox.cn/m1/3083103-0-default/emps/list'
        }).then((result) => {
            console.log(result.data);
        }).catch((err) => {
            console.log(err);
        });
    })
    
    //发送POST请求
    document.querySelector('#btnPost').addEventListener('click', () => {
        axios({
            method:'POST',
            url:'https://mock.apifox.cn/m1/3083103-0-default/emps/update',
            data:'id=1'
        }).then((result) => {
            console.log(result.data);
        }).catch((err) => {
            console.log(err);
        });
    })
</script>

简化,推荐

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    //发送GET请求
    document.querySelector('#btnGet').addEventListener('click', () => {
  axios.get('https://mock.apifox.cn/m1/3083103-0-default/emps/list').then((result) => {
      console.log(result.data);
    }).catch((err) => {
      console.log(err);
    });
})
    
    //发送POST请求
    document.querySelector('#btnPost').addEventListener('click', () => {
    axios.post('https://mock.apifox.cn/m1/3083103-0-default/emps/update', 'id=1').then((result) => {
      console.log(result.data);
    }).catch((err) => {
      console.log(err);
    });
})
</script>

同步操作

可以通过async、await可以让异步变为同步操作。async就是来声明一个异步方法,await是用来等待异步任务执行。

修改前:

search() {
    //基于axios发送异步请求,请求https://web-server.itheima.net/emps/list,根据条件查询员工列表
    axios.get(`https://web-server.itheima.net/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&job=${this.searchForm.job}`).then(res => {
      this.empList = res.data.data
    })
  }

修改后:方法前加async,请求前加await

  async search() {
    //基于axios发送异步请求,请求https://web-server.itheima.net/emps/list,根据条件查询员工列表
    const result = await axios.get(`https://web-server.itheima.net/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&job=${this.searchForm.job}`);
    this.empList = result.data.data;
  },