• Vue3+Typescript+Axios封装网络请求


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

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

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

    1. import type { AxiosRequestConfig, AxiosResponse } from 'axios';
    2. import axios from 'axios';
    3. import { showToast } from 'vant';
    4. const statusCode: any = {
    5. 200: '服务器成功返回请求的数据',
    6. 201: '新建或修改数据成功。',
    7. 202: '一个请求已经进入后台排队(异步任务)',
    8. 204: '删除数据成功',
    9. 400: '请求错误(400)',
    10. 401: '未授权,缺少令牌',
    11. 403: '拒绝访问(403)',
    12. 404: '请求出错(404)',
    13. 408: '请求超时(408)',
    14. 500: '服务器错误(500)',
    15. 501: '服务未实现(501)',
    16. 502: '网络错误(502)',
    17. 503: '服务不可用(503)',
    18. 504: '网络超时(504)',
    19. };
    20. const http = axios.create({
    21. baseURL: import.meta.env.VITE_APP_BASE_API,
    22. timeout: 5000,
    23. });
    24. // 请求拦截器
    25. http.interceptors.request.use(
    26. (config) => {
    27. return config;
    28. },
    29. (error) => {
    30. return Promise.reject(error);
    31. }
    32. );
    33. // 响应拦截器
    34. http.interceptors.response.use(
    35. (response: AxiosResponse) => {
    36. // todo
    37. return response.data;
    38. },
    39. (error) => {
    40. const response = Object.assign({}, error.response);
    41. response &&
    42. showToast(
    43. statusCode[response.status] || '系统异常, 请检查网络或联系管理员!'
    44. );
    45. return Promise.reject(error);
    46. }
    47. );
    48. interface responseData {
    49. code: number;
    50. data: T;
    51. msg: string;
    52. }
    53. const request = (
    54. config: AxiosRequestConfig
    55. ): Promise> => {
    56. return new Promise((resolve, reject) => {
    57. http
    58. .request(config)
    59. .then((res: AxiosResponse) => resolve(res.data))
    60. .catch((err: { message: string }) => reject(err));
    61. });
    62. };
    63. export default request;

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

    1. import request from './http.ts';
    2. /**
    3. * @description: 用户登录
    4. * @params data
    5. */
    6. export const loginAPI = (data: any) => {
    7. return request({
    8. url: '/user/login', // mock接口
    9. method: 'post',
    10. data,
    11. });
    12. };
    13. /**
    14. * @description: 获取用户信息
    15. * @returns
    16. */
    17. export const userInfo = () => {
    18. return request({
    19. url: '/user/info', // mock接口
    20. method: 'get',
    21. });
    22. };

     

  • 相关阅读:
    Leetcode1833. 雪糕的最大数量
    minio之分布式安装
    计算机网络 | 刷题笔记
    什么?“裸辞”一个月拿到13家offer,网友:你是在找存在感吗···
    WSUS 修补程序管理的替代方法
    Linux进程概念
    3分钟了解 egg.js
    CF1705D Mark and Lightbulbs
    url在api测试工具可以访问,但在浏览器不能访问
    归纳总结笔记
  • 原文地址:https://blog.csdn.net/weixin_45822952/article/details/136316330