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)
})
相关推荐
竹林8181 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
农夫山泉不太甜1 小时前
Tauri v2 实战代码示例
前端
yuhaiqiang1 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
红色石头本尊1 小时前
1-umi-前端工程化搭建
前端
真夜2 小时前
关于对echart盒子设置百分比读取的宽高没有撑开盒子解决方案
前端
楠木6852 小时前
RAG 资料库 Demo 完整开发流程
前端·ai编程
肠胃炎2 小时前
挂载方式部署项目
服务器·前端·nginx
像我这样帅的人丶你还2 小时前
使用 Next.js + Prisma + MySQL 开发全栈项目
前端
FPGA小迷弟2 小时前
FPGA 时序约束基础:从时钟定义到输入输出延迟的完整设置
前端·学习·fpga开发·verilog·fpga
Kel2 小时前
深入剖析 openai-node 源码:一个工业级 TypeScript SDK 的架构之美
javascript·人工智能·架构