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
{ - code: number;
- data: T;
- msg: string;
- }
-
- const request =
( - config: AxiosRequestConfig
- ): Promise
> => { - return new Promise((resolve, reject) => {
- http
- .request
(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',
- });
- };