欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 【陪诊系统-PC管理端】axios的二次封装

【陪诊系统-PC管理端】axios的二次封装

2025/2/23 14:36:45 来源:https://blog.csdn.net/Zheng113/article/details/141864881  浏览:    关键词:【陪诊系统-PC管理端】axios的二次封装

二次封装axios

  1. 引入axios
  2. 创建axios实例,添加配置信息,这里主要设置基础url和请求超时时间
  3. 给上述创建的实例添加拦截器,对请求、响应分别进行拦截
    根据接口文档显示,当登录成功后,每次请求陪诊师、订单信息都需要携带token,所以在后续请求发送前需要在请求头上添加上这个token(token是登录成功后,服务端返回的,然后被存储到本地)
  4. 请求拦截:设置白名单,因为在登录成功前的注册(获取验证码和验证验证码、登录),是不需要携带token的,所以将它排除
  5. 响应拦截:根据返回的响应数据(状态码)进行判断,看看是否数据异常,然后给出相应操作

request.js

import axios from 'axios'
import { ElMessage } from 'element-plus'const http = axios.create({baseURL: 'https:/v3pz.itndedu.com/v3pz',timeout: 10000,headers: { 'X-Custom-Header': 'foobar' }
});// 添加拦截器
// 添加请求拦截器
http.interceptors.request.use(function (config) {// 在发送请求之前做些什么// token作用户鉴权const token = localStorage.getItem('pz_token')// 不需要添加token的apiconst whiteUrl = ['/get/code', '/user/authentication', '/login']if (token && !whiteUrl.includes(config.url)) {config.headers['X-token'] = token}return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});// 添加响应拦截器
http.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么// 对接口异常的数据 给用户提示if (response.data.code === -1) {ElMessage.warning(response.data.message)}if (response.data.code === -2) {// token错误 清楚缓存localStorage.removeItem('pz_token')localStorage.removeItem('pz_userInfo')localStorage.removeItem('pz_v3pz')//window.location.orgin 当前页面路由window.location.href = window.location.orgin}return response;
}, function (error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么return Promise.reject(error);
});export default http

接口文件

使用二次封装后的axios进行请求,在api.js中定义所有的请求函数,最后到具体的某个地方再调用

import request from '../utils/request'// 发送验证码
export const getCode = (data) => {//发送post请求 data是参数return request.post('/get/code', data)
}
// 注册用户
export const UserAuthentication = (data) => {return request.post('/user/authentication', data)}
// 登录
export const login = (data) => {return request.post('/login', data)
}
// 权限管理
export const authAdmin = (params) => {return request.get('/auth/admin', { params })
}

具体调用

具体某个功能组件中调用api中的对应接口来发送真正的请求,这里在登录界面调用获取验证码请求。

import {getCode,UserAuthentication,login,menuPermissions} from '../../api'getCode({tel:loginForm.userName}).then((data)=>{// console.log('data',data);if(data.code === 10000){ElMessage.success('发送成功')}})

文件结构
在这里插入图片描述

that’s all!

版权声明:

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

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