赞
踩
import axios, { InternalAxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios'; import router from "/@/router"; import { showToast } from "vant"; import { getToken, removeToken } from "/@/utils/auth"; // 进度条 import nprogress from "nprogress"; import "nprogress/nprogress.css"; const service: AxiosInstance = axios.create({ baseURL: import.meta.env.VITE_GLOB_BASE_URL, // URL地址 timeout: 120 * 1000, // 超时时间 }); // 添加请求拦截器 service.interceptors.request.use( (config: InternalAxiosRequestConfig) => { // 在发送请求之前做些什么 nprogress.start(); config.headers = { nonce: Date.parse(new Date().toString()), clientType: "H5", clientVersion: "2.2.1", timestamp: Date.parse(new Date().toString()), Authorization: getToken() ? "Bearer " + getToken() : null, }; return Promise.resolve(config); }, (error: any) => { // 处理请求错误 return Promise.reject(error); }, ); // 添加响应拦截器 service.interceptors.response.use( (response: AxiosResponse<any>) => { // 对响应数据做点什么 const res = response.data; console.log('response:', res); if (res.code != 1) { // 500005 用户没有token或者过期 if (res.code == 500005) { removeToken(); localStorage.removeItem("userInfo"); router.replace({ path: "/login" }); nprogress.done(); } if (res.code == 100001 || res.code == 2000) { nprogress.done(); showToast(res.msg); } return Promise.reject(); } else { nprogress.done(); return Promise.resolve(res); } }, (error: any) => { // 处理响应错误 return Promise.reject(error); }, ); export default service;
import request from "/@/utils/request";
enum Api {
sysBannerList = '/goodsBanner/list', // banner 列表
sysHomeMenuList = '/homeMenu/getList', // 菜单列表
sysWeChatSignStr = '/v1/roles/roleEdit', // jssdk 签名接口
}
// banner 列表
export const bannerList = () => request.get(Api.sysBannerList);
// 菜单列表
export const getMenuList = () => request.get(Api.sysHomeMenuList);
// jssdk 签名接口
export const getWeChatSignStr = (params: any) => request.get<any>(Api.sysWeChatSignStr, { params });
简要说明几点:
1 . 适合有一丢丢经验的同学来看
2 . 比如: import { getToken, removeToken } from “/@/utils/auth”; 就是对获取token的方法就行简单封装了一下,对于经常写项目的同学应该都很清楚
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。