欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > vue3项目搭建-6-axios 基础配置

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

2025/5/16 17:22:06 来源:https://blog.csdn.net/m0_75138009/article/details/144105287  浏览:    关键词:vue3项目搭建-6-axios 基础配置

axios 基础配置

安装 axios

npm install axios

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

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

// 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

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

在 main.js 中调用:

//测试接口函数
import {getCategory} from '@/apis/testAPI'
getCategory().then(res => {console.log(res)
})

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词