当前位置: 首页 > article >正文

使用 Axios 进行高效的数据交互

一、前言

1. 项目背景与目标

  • Axios 的重要性
    • Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js,简化了与服务器的通信。
    • Axios 提供了丰富的功能,如拦截器、并发请求管理、取消请求等。

2. 环境搭建

  • 开发工具准备

    • 推荐使用 VSCode 或 WebStorm。
    • 安装必要的扩展如 Vetur(Vue 支持)、ESLint 等。
  • Axios 安装与配置

    • 使用 npm 或 yarn 安装 Axios:npm install axios
    • 在项目中引入 Axios。
    import axios from 'axios';
    
    // 创建 Axios 实例
    const instance = axios.create({
         
      baseURL: 'https://api.example.com',
      timeout: 1000,
    });
    
    export default instance;
    

二、Axios 基础

1. Axios 简介

  • Axios 的特点与优势

    • 基于 Promise 的 API,易于使用。
    • 支持浏览器和 Node.js。
    • 自动转换 JSON 数据。
    • 客户端支持防止 CSRF。
  • 安装与引入

    • 使用 npm 或 yarn 安装 Axios。
    • 在项目中引入 Axios 实例。

2. 基本用法

  • 发送 GET 请求

    axios.get('/users')
      .then(response => {
         
        console.log(response.data);
      })
      .catch(error => {
         
        console.error('Error fetching users:', error);
      });
    
  • 发送 POST 请求

    axios.post('/users', {
          name: 'John' })
      .then(response => {
         
        console.log('User created:', response.data);
      })
      .catch(error => {
         
        console.error('Error creating user:', error);
      });
    
  • 处理响应数据

    • 使用 .then() 处理成功响应。
    • 使用 .catch() 处理错误。
    axios.get('/users')
      .then(response => {
         
        console.log('Data:', response.data);
      })
      .catch(error => {
         
        console.error('Error:', error);
      });
    

三、高级特性

1. 拦截器

  • 请求拦截器

    • 在请求发送前进行处理。
    axios.interceptors.request.use(
      config => {
         
        console.log('Request sent:', config);
        return config;
      },
      error => {
         
        console.error('Request error:', error);
        return Promise.reject(error);
      }
    );
    
  • 响应拦截器

    • 在接收到响应后进行处理。
    axios.interceptors.response.use(
      response => {
         
        console.log('Response received:', response);
        return response;
      },
      error => {
         
        console.error('Response error:', error);
        return Promise.reject(error);
      }
    );
    

2. 并发请求

  • 使用 axios.allaxios.spread
    axios.all([
      axios.get('/users'),
      axios.get('/posts')
    ])
    .then(axios.spread((usersResponse, postsResponse) => {
         
      console.log('Users:', usersResponse.data);
      console.log('Posts:', postsResponse.data);
    }))
    .catch(error => {
         
      console.error('Error:', error);
    });
    

3. 取消请求

  • 使用 CancelToken 取消请求
    import axios from 'axios';
    
    const CancelToken = axios.CancelToken;
    let cancel;
    
    axios.get('/users', {
         
      cancelToken: new CancelToken(function executor(c) {
         
        cancel = c;
      })
    })
    .then(response => {
         
      console.log(response.data);
    })
    .catch(error => {
         
      if (axios.isCancel(error)) {
         
        console.log('Request canceled', error.message);
      } else {
         
        console.error('Error:', error);
      }
    });
    
    // 取消请求
    cancel('Operation canceled by the user.');
    

4. 超时设置

  • 设置请求超时时间
    axios.get('/users', {
         
      timeout: 5000
    })
    .then(response => {
         
      console.log(response.data);
    })
    .catch(error => {
         
      console.error('Error:', error);
    });
    

四、状态管理与数据流

1. Vuex 状态管理模式

  • 创建 Vuex Store
    // store/index.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
         
      state: {
         
        users: []
      },
      mutations: {
         
        SET_USERS(state, users) {
         
          state.users = users;
        }
      },
      actions: {
         
        fetchUsers({
           commit }) {
         
          axios.get('/users')
            .then(response => {
         
              commit('SET_USERS', response.data);
            })
            .catch(error => {
         
              console.error('Error fetching users:', error);
            });
        }
      }
    });
    

2. 结合 Axios 进行异步操作

  • 在 Vuex Actions 中调用 Axios
    // UserList.vue
    <template>
      <div>
        <h1>User List</h1>
        <ul>
          <li v-for="user in u

http://www.kler.cn/a/536978.html

相关文章:

  • 第二个Qt开发实例:在Qt中利用GPIO子系统和sysfs伪文件系统实现按钮(Push Button)点击控制GPIO口(效果为LED2灯的灭和亮)
  • 软件系统性能测试的重要性和测试类型分享
  • Android 实现首页Tab切换并且支持懒加载功能详解
  • 深度分析:网站快速收录与网站内容多样性的关系
  • 基于docker搭建Kafka集群,使用KRaft方式搭建,摒弃Zookeeper
  • 初阶数据结构:树---堆
  • 各种协议设计
  • (2025|Meta,LLM,token 压缩/挑选,离散潜在标记,VQ-VAE)混合潜在标记和文本标记以改进语言模型推理
  • 详解正则表达式与案例
  • DOMParser解析TikTok页面中的图片元素
  • C# 中 Guid类 使用详解
  • Python3+Request+Pytest+Allure+Jenkins 接口自动化测试[手动写的和AI写的对比]
  • 3. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--什么是微服务--微服务的核心特性与设计理念
  • UE求职Demo开发日志#23 线性任务系统数据层实现
  • zephyr devicetree
  • Android 多环境(生产、测试、开发)多域名网络配置
  • 一次报警了解:direct path read、enq: KO - fast object checkpoint
  • 【C语言】文件操作详解 - 从打开到关闭
  • STM32的HAL库开发---高级定时器---输出比较模式实验
  • Java 多线程、线程同步、线程池
  • C# LiteDB 使用教程
  • Qt实现简易音乐播放器
  • 脚手架开发【实战教程】prompts + fs-extra
  • MySQL视图索引操作
  • 【Linux】Ubuntu Linux 系统 ——Android开发环境
  • linux进程通讯-信号处理介绍