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

第一步:安装axios

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

复制代码
npm install axios

第二步:创建 Axios 实例

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

javascript 复制代码
// 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 实例并使用它来发送请求:

javascript 复制代码
<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>
相关推荐
wuhuhuan1 小时前
【JMeter 学习打卡 Day 4】多用户登录 + 动态 token 关联
学习·jmeter
Code额2 小时前
Python asyncio 异步编程全套学习文档(零基础完整版)
python·学习·oracle·async·异步·asyncio
在线考试系统推荐3 小时前
2026年7月最新实测:三大考试软件导入试题能力对比
人工智能·学习·系统架构
小弥儿3 小时前
GitHub今日热榜 | 2026-08-20:Agent 上下文数据库接棒
数据库·学习·开源·github
sunoo-2293 小时前
【C 语言标准 IO 入门】第二天学习笔记:文件操作核心函数 + 实战案例 + 踩坑合集
linux·笔记·vscode·学习
MartinYeung53 小时前
[论文学习]MPMA:针对模型上下文协议的偏好操纵攻击
人工智能·学习·安全
我爱cope4 小时前
【计算机网络 | 数据链路层8:CSMA/CD 与 CSMA/CA:有线以太网和 Wi-Fi 如何避免冲突?】
网络·学习·计算机网络
-To be number.wan5 小时前
我的创作纪念日
学习
爱吃火鸡面呀5 小时前
NumPy 从入门到精通:一份完整的高质量学习路线与实践指南
学习·numpy
for_ever_love__5 小时前
SQL学习: SQL入门与DDL
数据库·sql·学习