Vue3学习:如何在Vue3项目中创建一个axios实例

第一步:安装axios

首先,确保你的项目中已经安装了 Axios。如果还没有安装,可以通过 npm 或 yarn 来安装:

npm install axios

第二步:创建 Axios 实例

接下来,可以在项目的某个合适的位置(比如 src/utils/ 目录下)创建一个新的 JavaScript 文件,例如 axiosInstance.js,并在该文件中创建 Axios 实例:

// src/utils/axiosInstance.js
import axios from 'axios';

// 创建 Axios 实例
const api = axios.create({
  baseURL: '你的API基础URL', // e.g., 'https://api.example.com'
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    // 可以在这里添加其他默认请求头,如认证token等
  },
});

// 添加请求拦截器(可选)
api.interceptors.request.use(config => {
  // 在发送请求之前做些什么,例如添加Token
  // config.headers.Authorization = `Bearer ${token}`;
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器(可选)
api.interceptors.response.use(response => {
  // 对响应数据做点什么,例如错误码处理
  return response.data;
}, error => {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default api;

第三步:在 Vue 组件中使用 Axios 实例

最后,在需要发送HTTP请求的 Vue 组件中,导入刚刚创建的 Axios 实例并使用它来发送请求:

<template>
  <!-- ... -->
</template>

<script setup>
import axiosInstance from '@/utils/axiosInstance';

async function fetchData() {
  try {
    const response = await axiosInstance.get('/your-endpoint');
    console.log(response);
  } catch (error) {
    console.error('There was an error!', error);
  }
}
</script>

<style scoped>
<!-- ... -->
</style>

相关推荐

  1. Vue3学习如何Vue3项目创建axios实例

    2024-07-16 12:14:01       25 阅读
  2. Vue创建vue3项目

    2024-07-16 12:14:01       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 12:14:01       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 12:14:01       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 12:14:01       62 阅读
  4. Python语言-面向对象

    2024-07-16 12:14:01       72 阅读

热门阅读

  1. 机器学习中的LeetCode

    2024-07-16 12:14:01       22 阅读
  2. 安全加固:Eureka服务实例安全令牌配置全解析

    2024-07-16 12:14:01       29 阅读
  3. Linux 环境下整体备份迁移 Docker 镜像及数据教程

    2024-07-16 12:14:01       28 阅读
  4. Uniapp中image的@load不触发问题

    2024-07-16 12:14:01       26 阅读
  5. unity局部坐标和世界坐标角度介绍

    2024-07-16 12:14:01       28 阅读
  6. windows下使用#include <nlohmann/json.hpp>

    2024-07-16 12:14:01       20 阅读
  7. C# winform 打印Excel

    2024-07-16 12:14:01       23 阅读
  8. Linux容器篇-kubernetes监控和日志管理

    2024-07-16 12:14:01       24 阅读
  9. PG参数深入了解

    2024-07-16 12:14:01       22 阅读