欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > axios二次封装

axios二次封装

2025/11/13 17:12:07 来源:https://blog.csdn.net/jkjkikik/article/details/142340329  浏览:    关键词:axios二次封装

axios的使用以及二次封装

  • 一:axios的使用
  • 二:vue中的二次封装
    • 1.终端下载
    • 2.main.js中引入
    • 3.封装axios实例--http.js
    • 4.添加请求拦截器
    • 5.添加响应1拦截器
    • 6.封装请求API
    • 7.组件内使用

一:axios的使用

1.下载

npm i axios -S

2.引入

import axios from 'axios'

3.使用
axios.get()
axios.post()
axios({
url:‘’,
method:‘’,
data:‘post传值方式’
}).then(res=>
console.log(res)//后端给前端返回的数据
)

二:vue中的二次封装

1.终端下载

npm i axios -S

2.main.js中引入

import axios from "axios";

3.封装axios实例–http.js

引入相关内容并创建axios实例

// axios的二次封装
// 引入axios
import axios from 'axios'
// 引入token
import {useUserStore} from '@/stores/userStore'
// 引入路由
// import { useRouter } from 'vue-router';
import router from '@/router';
// 创建axios实例
const httpInstance = axios.create({// 设置基地址baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',//  设置超时时间timeout: 20000
})

4.添加请求拦截器

config参数
config 对象是由 Axios 库在内部创建并传递给拦截器函数的。当你使用 Axios 发起一个 HTTP 请求时,Axios 会根据你提供的请求配置选项(如 URL、方法、头信息等)创建一个 config 对象。这个对象包含了请求的所有必要信息。
添加响应拦截器并导出

// 拦截器
// 添加请求拦截器
httpInstance.interceptors.request.use(function (config) {const useStore=useUserStore()// 1.从pinia获取token数据const token=useStore.userInfo.token// 在发送请求之前做些什么//判断token是否存在if(token){//将token按照后端的要求拼接一下,并且加到请求头上面。config.headers.Authorization=`Bearer ${token}`}//将修改后的config返回出去return config;}, //没有获取到token,返回错误function (error) {// 对请求错误做些什么return Promise.reject(error);});

5.添加响应1拦截器

httpInstance.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 拿到reponse之后可以对响应数据做一些操作return response;}, function (error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么// 利用拦截器做了一个统一的配置,为什么要写在拦截器里面,因为有很多共同的操作会报错ElMessage({message:error.response.data.msg,type: 'warning',})// 401token失效处理const userStore=useUserStore()// 2.跳转到登录页if(error.response.status===401){// 1.清除本地用户数据userStore.clearUserInfo()// 2.跳转到登录页router.push('/login')}// 返回错误提示return Promise.reject(error);}); 
// 导出
export default httpInstance

6.封装请求API

// 获取详情接口,实例里面有请求拦截器,响应拦截器,超时时间,请求基地址。
import httpInstance from "@/utils/http";
export const getCheckoutInfoAPI = () => {return httpInstance({url:'/member/order/pre'})}
export const createOrderAPI=(data)=>{
return httpInstance({url:'/member/order',method:'POST',data
})
}

7.组件内使用

//引入相关发送请求的API
import {getCategoryFilterAPI,getSubCategoryAPI} from '@/apis/category.js'
import { onMounted} from 'vue'
// 获取面包屑导航数据
//创建容器
const categoryData=ref([])
const getCategoryData=async ()=>{
//调用API并传入参数const res=await getCategoryFilterAPI(route.params.id)categoryData.value=res.data.result
}
onMounted(()=>{getCategoryData() 
})

版权声明:

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

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