axios

发布时间 2023-09-09 11:49:22作者: SimpleWord
title: axios
index_img: https://tuchuangs.com/imgs/2023/08/19/2ac41dcb56786d1d.png
tags:
  - Java Web
  - 前端
  - Vue
categories:
  - Java Web
excerpt: axios

使用axios

安装

npm install axios

引入和使用

  • created() 是 Vue 实例的一个生命周期钩子。可用于发送网络请求。
    • Vue 实例已经完全创建,可以访问到实例中的所有属性和方法
  • 但该阶段组件并未挂载至DOM,所以如果你需要操作DOM,则应该放在 mounted() 钩子函数
<script>
import axios from 'axios';

export default {
  data() {
    return {
      // 初始化 posts 数据属性为空
      posts: null
    };
  },
  created() {
    // 在 Vue 实例创建完成后,发送 GET 请求获取数据
    axios.get('https://api.example.com/posts')
      .then(response => {
        // 当请求成功时,将返回的数据保存到 posts 数据属性中
        this.posts = response.data;
      })
      .catch(error => {
        // 如果请求失败,打印错误信息
        console.log(error);
      });
  }
};
</script>

请求格式

Get

// 使用 axios 发送 GET 请求到指定的 URL 
axios.get('/api/url')
  .then(response => {
    // 当请求成功时,打印返回的数据
    console.log(response.data);
  })
  .catch(error => {
    // 如果请求失败,打印错误信息
    console.error(error);
  });

Post

// 使用 axios 发送 POST 请求到指定的 URL,并且传递了两个参数
axios.post('/api/url', {
  param1: 'value1',
  param2: 'value2'
})
.then(response => {
  // 当请求成功时,打印返回的数据
  console.log(response.data);
})
.catch(error => {
  // 如果请求失败,打印错误信息
  console.error(error);
});

Put

// 使用 axios 发送 PUT 请求到指定的 URL,并且更新了两个参数
axios.put('/api/url', {
  param1: 'updatedValue1',
  param2: 'updatedValue2'
})
.then(response => {
  // 当请求成功时,打印返回的数据
  console.log(response.data);
})
.catch(error => {
  // 如果请求失败,打印错误信息
  console.error(error);
});

Delete

// 使用 axios 发送 DELETE 请求到指定的 URL
axios.delete('/api/url')
  .then(response => {
    // 当请求成功时,打印返回的数据
    console.log(response.data);
  })
  .catch(error => {
    // 如果请求失败,打印错误信息
    console.error(error);
  });

拦截器

可以简化请求,见Vue脚手架