Vue3+Typescript+Axios封装网络请求

1、执行 npm i axios 命令安装Axios;

2、在src目录下新建utils文件夹;

3、在src/utils 目录下新建https.ts文件

import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
import { showToast } from 'vant';
const statusCode: any = {
  200: '服务器成功返回请求的数据',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)',
  204: '删除数据成功',
  400: '请求错误(400)',
  401: '未授权,缺少令牌',
  403: '拒绝访问(403)',
  404: '请求出错(404)',
  408: '请求超时(408)',
  500: '服务器错误(500)',
  501: '服务未实现(501)',
  502: '网络错误(502)',
  503: '服务不可用(503)',
  504: '网络超时(504)',
};

const http = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse) => {
    // todo
    return response.data;
  },
  (error) => {
    const response = Object.assign({}, error.response);
    response &&
      showToast(
        statusCode[response.status] || '系统异常, 请检查网络或联系管理员!'
      );
    return Promise.reject(error);
  }
);

interface responseData<T> {
  code: number;
  data: T;
  msg: string;
}

const request = <T = unknown>(
  config: AxiosRequestConfig
): Promise<responseData<T>> => {
  return new Promise((resolve, reject) => {
    http
      .request<T>(config)
      .then((res: AxiosResponse) => resolve(res.data))
      .catch((err: { message: string }) => reject(err));
  });
};

export default request;

4、在src/utils 目录下新建api.ts文件

import request from './http.ts';

/**
 * @description: 用户登录
 * @params data
 */
export const loginAPI = (data: any) => {
  return request({
    url: '/user/login', // mock接口
    method: 'post',
    data,
  });
};

/**
 * @description: 获取用户信息
 * @returns
 */
export const userInfo = () => {
  return request({
    url: '/user/info', // mock接口
    method: 'get',
  });
};

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值