axios封装

该代码实现了一个基于axios的HTTP请求库,根据环境变量动态配置请求的基础URL,包括代理和生产环境的域名。同时,它包含请求和响应拦截器,处理请求头、超时以及HTTP状态码。此外,定义了post和get函数,支持不同数据返回级别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fetch.ts

import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig } from 'axios';

const {
	NODE_ENV, // 环境变量
	REACT_APP_ENV // 环境标识
} = process.env;

// 是否为 mock 环境
const IS_MOCK = REACT_APP_ENV === 'mock';

// 是否为生产模式
const IS_PROD = NODE_ENV === 'production';

// 根据地址栏 path 确定请求二级 path
const pathname = window.location.pathname.split('/')[3] || '/';

const DEFAULT_SYMBOL = pathname === '/' ? 'device' : pathname;

// 开发环境: 代理标识
const PROXY_SYMBOL = IS_MOCK ? REACT_APP_ENV : `${DEFAULT_SYMBOL}-api`;

// 生产环境: 正式域名
const HOST_URL = process.env[`REACT_APP_HOST_${DEFAULT_SYMBOL.toUpperCase()}`];

// 基础URL
const baseurl = IS_PROD ? HOST_URL : PROXY_SYMBOL;

const dio: AxiosInstance = axios.create({
	// 设置baseUr地址,如果通过proxy跨域可直接填写base地址
	baseURL: baseurl,

	// 定义统一的请求头部
	headers: {
		'Content-Type': 'application/json'
	},

	// 配置请求超时时间
	timeout: 10000,
	// http 状态码判断
	validateStatus(status: number) {
		switch (status) {
			case 404:
				console.error('失去页面页');
				break;
			case 500:
				console.error('服务错误页');
				break;
			default:
				console.log('http码正常');
				break;
		}
		return status < 500;
	}
});
// 请求拦截
dio.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		if (config.headers) {
			const header = config.headers;
			// header['Authorization'] = sessionStorage.getItem('Authorization');
		}
		return config;
	},
	error => {
		console.error('request interceptors', error);
	}
);

// 响应拦截
dio.interceptors.response.use(
	response => {
		// if ('headers' in response) sessionStorage.setItem('Authorization', response.headers.Authorization as string);
		return response;
	},
	error => Promise.reject(error)
);

export default dio;

dio.ts

import { AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from './fetch';

type TDatalevel = 'data' | 'serve' | 'axios';
type RServe<T> = Promise<BaseResponse<T>>;
type RAxios<T> = Promise<AxiosResponse<BaseResponse<T>>>;
interface BaseResponse<T> {
	code: number;
	message: string;
	success: boolean;
	data: T;
}

function post<D, T>(url: string, data: D, datalevel?: 'data', config?: AxiosRequestConfig<D>): Promise<T>;
function post<D, T>(url: string, data: D, datalevel?: 'serve', config?: AxiosRequestConfig<D>): RServe<T>;
function post<D, T>(url: string, data: D, datalevel?: 'axios', config?: AxiosRequestConfig<D>): RAxios<T>;
function post<D, T>(url: string, data: D, datalevel: TDatalevel = 'data', config?: AxiosRequestConfig<D>) {
	return axios.post<D, AxiosResponse<BaseResponse<T>>>(url, data, config).then(res => {
		if (!res.data.success) throw res.data as BaseResponse<T>;
		switch (datalevel) {
			case 'data':
				return res.data.data;
			case 'serve':
				return res.data;
			case 'axios':
				return res;
		}
	});
}

function get<D, T>(url: string, config?: AxiosRequestConfig<D>, datalevel?: 'data'): Promise<T>;
function get<D, T>(url: string, config?: AxiosRequestConfig<D>, datalevel?: 'serve'): RServe<T>;
function get<D, T>(url: string, config?: AxiosRequestConfig<D>, datalevel?: 'axios'): RAxios<T>;
function get<D, T>(url: string, config?: AxiosRequestConfig<D>, datalevel: TDatalevel = 'data') {
	return axios.get<D, AxiosResponse<BaseResponse<T>>>(url, config).then(res => {
		if (!res.data.success) throw res.data as BaseResponse<T>;
		switch (datalevel) {
			case 'data':
				return res.data.data;
			case 'serve':
				return res.data;
			case 'axios':
				return res;
		}
	});
}

export { post, get };

type.ts

interface Ilist {
	title: string;
	agree: boolean;
	price: number;
	image: string;
	name: string;
	skuid: string;
	sort: number;
	cccc: number;
}
export interface Ilogin {
	aaa: string[];
	list: Ilist[];
}

index.ts

import { AxiosRequestConfig } from 'axios';
import { get, post } from './dio';
import type { Ilogin } from './type';
/**
 * 登录
 */
export const login = (_?: undefined) => post<unknown, Ilogin>('getTime', _, 'serve');

/**
 * 随机一句名言
 */
export const vote = (param: AxiosRequestConfig<unknown>) => get('sentences', param, 'axios');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gleason.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值