赞
踩
直接使用axios,依赖性太强,今后如要换网络请求库会很麻烦
一些公共的请求功能,每次请求都需要重写配置
将
aixos
进行加一层封装,将一些公共的功能封装,如网络请求头添加Authorization
(即token
),加载loading
效果等等,拦截器也可以灵活封装
在
utils
创建utils/request.ts
文件
- import axios, { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios"
- import { ElLoading } from 'element-plus'
-
- interface Result<T = any> {
- code: number | string;
- msg: string;
- data: T;
- total: number;
- };
-
-
- // 导出Request类,可以用来自定义传递配置来创建实例
- class HttpRequest {
- baseURL: string;
- timeout: number;
-
- constructor() {
- this.baseURL = import.meta.env.VITE_APP_BASE_API;
- this.timeout = 60000
- }
-
- request<T = any>(options: AxiosRequestConfig): Promise<Result<T>> {
- // axios 实例
- const instance: AxiosInstance = axios.create()
- this.setInterceptors(instance)
- const opts = this.mergeOptions(options)
- return instance(opts)
- }
-
- get<T = any>(url: string, data?: any, outHeaders = {}): Promise<Result<T>> {
- return this.request<T>({
- method: 'get',
- url,
- params: { ...data }, // get参数可以直接展开
- headers: {}
- })
- }
-
- post<T = any>(url: string, body = {}, outHeaders = {}): Promise<Result<T>> {
- let data = {
- body,
- header: {}
- }
- return this.request<T>({
- method: 'post',
- url,
- data, // post要求必须传入data属性
- })
- }
- mergeOptions(options: AxiosRequestConfig) {
- //console.log('合并参数', options)
- return {
- baseURL: this.baseURL,
- timeout: this.timeout,
- ...options
- }
- }
- // 设置拦截器
- setInterceptors(instance: AxiosInstance) {
- let loading: any
- // 请求拦截器
- instance.interceptors.request.use((config) => {
- loading = ElLoading.service({
- lock: true,
- text: 'Loading',
- background: 'rgba(0, 0, 0, 0.7)',
- })
- // 一般会请求拦截里面加token,用于后端的验证
- /* const token = localStorage.getItem("token")
- config!.headers!.Authorization = token
- config.headers = Object.assign(config.headers, { ...config.headers, token }); */
-
- return config
- },
- (err: any) => {
- console.log(err);
- return Promise.reject(err);
- })
-
- // 响应拦截器
- instance.interceptors.response.use(
- (res) => {
- console.log("声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/82171推荐阅读
相关标签
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。