1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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;
- });
- }
- // 封装文件上传请求
- export async function uploadFile(url: string, data?: any): Promise<any> {
- return instance
- .post(url, data, {
- headers: {
- "Content-type": "multipart/form-data",
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw error;
- });
- }
|