vue3项目搭建-6-axios 基础配置

axios 基础配置

安装 axios

复制代码
npm install axios

创建 axios 实例,配置基地址,配置拦截器,目录:utils/http.js

基地址:在每次访问时,自动作为相对路径的根

javascript 复制代码
// axios 基础封装
import axios from "axios";

const httpInstance = axios.create({
    // 项目基地址
    // baseURL:'https://localhost:8888/api',
    baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000
})
// 创建完记得暴露该实例
export default httpInstance

// 添加请求拦截器
httpInstance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
httpInstance.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

测试路径连接,目录:aips/testAPI.js

javascript 复制代码
import httpInstance from '@/utils/http'

// 给实例传入具体路径,即在最末尾拼接 url
export function getCategory(){
    return httpInstance({
        url: 'home/category/head'
    })
}

在 main.js 中调用:

javascript 复制代码
//测试接口函数
import {getCategory} from '@/apis/testAPI'
getCategory().then(res => {
    console.log(res)
})
相关推荐
乘风gg1 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭2 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒2 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭2 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy3 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin4 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶4 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic4 小时前
本地通知(Local Notifications)学习笔记
前端
任沫4 小时前
Agent之Function Call
javascript·人工智能·go
森蓝情丶5 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端