123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import axios from "axios";
- import { showMessage } from "./errorStatusCode"; // 引入状态码文件
- import type { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
- import { ElNotification } from "element-plus";
- import { useStore } from "../store/index";
- const baseURL = "/api";
- // 创建axios实例
- const instance = axios.create({
- baseURL, // 设置API的基础URL
- });
- // 请求拦截器
- instance.interceptors.request.use(
- (config: AxiosRequestConfig): any => {
- // 可在请求发送前对config进行修改,如添加请求头等
- const { getToken } = useStore()
- const token = getToken
- const headers = config.headers || {};
- headers["Token"] = token;
- config.headers = headers;
- return config;
- },
- (error: AxiosError) => {
- // 处理请求错误
- return Promise.reject(error);
- }
- );
- // 响应拦截器
- instance.interceptors.response.use(
- (response: AxiosResponse) => {
- // 对响应数据进行处理
- if (response.status != 200) {
- ElNotification({
- message: showMessage(response.status), // 传入响应码,匹配响应码对应信息,
- type: "error",
- });
- }
- return response;
- },
- (error: AxiosError) => {
- // 处理响应错误
- return Promise.reject(error);
- }
- );
- // 封装GET请求
- export async function get(url: string, params?: any): Promise<any> {
- return instance
- .get(url, { params })
- .then((response) => response.data)
- .catch((error) => {
- throw error;
- });
- }
- // 封装POST请求
- export async function post(url: string, data?: any): Promise<any> {
- return instance
- .post(url, data, {
- headers: {
- "Content-type": " application/x-www-form-urlencoded; charset=UTF-8",
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw error;
- });
- }
|