React封装axios请求

1、前言

        因为最近在进行老系统用新框架改造,正好用到了react,就顺便整理了一下react中对axios进行封装的相关知识点和步骤。

2、如何封装

        可以参考一下chat gpt给出的回答。

        

 

         我大概总结一下,其实就是使用axios.create创建一个axios的实例,然后我们每次发get/post请求,都直接调用这个创建好的axios实例就行了。

3、相关代码

相关代码gitee地址:https://gitee.com/wulinchun/my-react-ts.git

Step1、创建一个typescript的react工程项目 。

npx create-react-app my-react-ts --template typescript

        如果不加 --template typescript,react默认建的是javascript工程。我之前去网上学习react的时候,许多教程都是基于js,jsx创建的react工程,但我在公司开发的react项目都是typescript的。typescript是javascript的增强版,我之前一直都是写javascript、jquery这套的,typescript之前没接触过。我没怎么系统学习过typescript语言,就我在实际工作开发而言。typescript增加了一些结构类型的定义。比如我在.ts里面可以定义一个interface结构用于接收后端的数据,interface结构中我可以详细的定义每一个变量的类型:string,number,boolean等等。不确定的类型则用any。相比较而言javascript就没这么强大。typescript的编译比javascript严格。javascript是弱类型的,只要不是什么涉及到计算的,你把一个字符串型的数值赋值给一个数值类型的变量也没啥问题。你直接用var定义就行了。但typescript就不可以了。

        不过从编译效率上来说的话,因为node.js不能直接执行.ts文件,因此编译的时候会多一步把typescript转为javascript,因此typescript要比javascript慢一点。 

关于typescript更多的了解可参考:

​​​​​​TypeScript 与 JavaScript:你应该知道的区别 - 掘金 (juejin.cn)

文档简介 · TypeScript中文网 · TypeScript——JavaScript的超集 (tslang.cn)

Step2、react前端代码

        这是我的工程目录结构

request.ts(用于封装axios实例)

import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
interface AxiosTokenInstance extends AxiosInstance {
   
}
// 创建一个axios实例
const instance: AxiosTokenInstance = axios.create({
    baseURL: '/',
    timeout: 5000,
    responseType: 'json',
    headers: {
      'Content-Type': 'application/json',
    },
  })

const {request,get,post} = instance;
//暴露axios实例
export {request,get,post,instance};

returnType.ts(接口返回值数据结构)

export interface ResType<R>{
    code:number;
    message:string;
    data:R;
}

setupProxy.js(配置代理,注意必须是.js代理文件,不能用setupProxy.ts,因为npm start启动的时候无法加载.ts的配置文件)

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://127.0.0.1:80',
            changeOrigin: true,
            pathRewrite: {
                '^/api': '',
            }
        })
    );
    app.use(
        '/api1',
        createProxyMiddleware({
            target: 'http://localhost:8082',
            changeOrigin: true,
            pathRewrite: {
                '^/api1': '',
            }
        })
    );
};

src\pages\Home\index.tsx(页面组件)

import React,{useState} from "react";
import {PeopleDTO,listAllPeople,getPeople,getPeople1,PeopleV2DTO} from './service'
import {useRequest} from 'ahooks';

const Home:React.FC=()=>{
    const [peopleDTOList,setpeopleDTOList]=useState<PeopleDTO[]>([]);

    const [age,setAge]=useState('')
    const [peopleId,setPeopleId]=useState('')
    const [peopleName,setPeopleName]=useState('')
    const [position,setPosition]=useState('')
    const [subordinateList,setSubordinateList]=useState<PeopleV2DTO[]>([]);

    const [searchContent, setSearchContent] = useState<string>('');



    const listPeople=()=>{
        //get请求无参数
        listAllPeople().then((response) => {
            const result = response.data;
             console.log(response);
             console.log(result);
             setpeopleDTOList(result.PeopleDTOList);
             console.log(peopleDTOList)
        });
    };

    const getOnePeople=()=>{
        //get请求带参数
        getPeople(searchContent).then((response) => {
            console.log(searchContent)
            const result = response.data;
            console.log(response);
            console.log(result);
            setAge(result.age);
            setPeopleId(result.peopleId);
            setPeopleName(result.peopleName);
            setPosition(result.position);
            setSubordinateList(result.subordinate);
        });
    };

    const getOnePeople1=()=>{
        //post请求带json参数
        getPeople1({PeopleId:searchContent}).then((response) => {
            console.log(searchContent)
            const result = response.data;
            console.log(response);
            console.log(result);
            setAge(result.age);
            setPeopleId(result.peopleId);
            setPeopleName(result.peopleName);
            setPosition(result.position);
            setSubordinateList(result.subordinate);
        });
    };


   
    return(
        <div>
            <h1>首页</h1>
            <button onClick={() => listPeople()}>listAllPeople</button>
            <input
               placeholder="请输入待搜索人员" 
               value={searchContent}
               onChange={(e) => {
                setSearchContent(e.target.value);
              }}
            />
            <button onClick={() => getOnePeople()}>getOnePeople</button>
            <button onClick={() => getOnePeople1()}>getOnePeople1</button>
            <table>
                <tbody>
                    {peopleDTOList.map((items, index)=>(
                        <tr key={index}>
                            <th>ID:</th><td>{items.peopleId}</td>
                            <th>姓名:</th><td>{items.peopleName}</td>
                            <th>年龄:</th><td>{items.age}</td>
                            <th>职位:</th><td>{items.position}</td>
                            <th>下属:</th>
                            <td>
                                {items.subordinate.map((it,idx)=>(
                                    <label key={idx}>{it.name}~{it.age}</label>
                                ))}
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    )
   
    

};

export default Home;

src\pages\Home\service.ts(定义数据结构以及请求后端接口)

import { get,post } from '../../../src/utils/request';
import {ResType} from '../../../src/utils/returnType'


export interface PeopleDTO {
    peopleId: string;
    peopleName: string;
    age: string;
    position: string;
    subordinate: PeopleV2DTO[];
}

export interface PeopleV2DTO {
    name: string;
    age: string;
}

export interface PeopleDTOList{
    PeopleDTOList: PeopleDTO[];
}

export interface PeopleId{
    PeopleId: string;
}

export const listAllPeople:(
) =>Promise<ResType<PeopleDTOList>>=()=>{
    return get('api/root/listPeople.asp')
}

export const getPeople:(
    params:string,
) =>Promise<ResType<PeopleDTO>>=(params)=>{
    return get(`api/root/getPeople.asp?PeopleId=${params}`,{})
};

export const getPeople1:(
    params:PeopleId,
) =>Promise<ResType<PeopleDTO>>=(params)=>{
    return post('api1/login/getPeople1',params)
};

src\index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Home  from './pages/Home';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    {/* <App /> */}
    <Home/>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Step3、后端接口

vbscript接口,部署在http://127.0.0.1:80上

1、/root/listPeople.asp

<%
Response.Charset="utf-8"
Set util=CreateObject("util.WSC")
Set bzExample=CreateObject("bzExample.WSC")

Set oJsonResponse = util.InitAspJson()


ReDim Preserve arrDetail(2,3)
arrDetail(0,0)="李五"
arrDetail(1,0)="20"

arrDetail(0,1)="王五"
arrDetail(1,1)="22"

arrDetail(0,2)="赵六"
arrDetail(1,2)="25"

'Response.Write Ubound(arrDetail,2)&"<br/>"

With oJsonResponse.data
   .Add "PeopleDTOList",oJsonResponse.Collection()
        With .item("PeopleDTOList")
            .Add 0,oJsonResponse.Collection()
            With .item(0)
                .Add "peopleId","zhangsan" 
                .Add "peopleName","张三"
                .Add "age","30"
                .Add "position","Manager" 
                .Add "subordinate",oJsonResponse.Collection()
                With .item("subordinate")
                    indexI = 0
                    for indexI=0 to Ubound(arrDetail,2)-1
                        'Response.Write "indexI="&indexI&"<br/>"
                        .Add indexI,oJsonResponse.Collection()
                        With .item(indexI)
                            .Add "name",arrDetail(0,indexI)
                            .Add "age",arrDetail(1,indexI)  
                        End With

                        'indexI = indexI +1
                    next
                End With
            End With

            .Add 1,oJsonResponse.Collection()
            With .item(1)
                .Add "peopleId","lisi" 
                .Add "peopleName","李四"
                .Add "age","40"
                .Add "position","Manager" 
                .Add "subordinate",oJsonResponse.Collection()
                With .item("subordinate")
                    indexI = 0
                    for indexI=0 to Ubound(arrDetail,2)-1
                        'Response.Write "indexI="&indexI&"<br/>"
                        .Add indexI,oJsonResponse.Collection()
                        With .item(indexI)
                            .Add "name",arrDetail(0,indexI)
                            .Add "age",arrDetail(1,indexI)  
                        End With

                        'indexI = indexI +1
                    next
                End With
            End With
        End With
End With

Response.Write oJsonResponse.JSONoutput()
%>

2、/root/getPeople.asp

<%
Response.Charset="utf-8"
Set util=CreateObject("util.WSC")
Set bzExample=CreateObject("bzExample.WSC")

Set oJsonResponse = util.InitAspJson()

peopleId=request("PeopleId")

ReDim Preserve arrDetail(2,3)
arrDetail(0,0)="李五"
arrDetail(1,0)="20"

arrDetail(0,1)="王五"
arrDetail(1,1)="22"

arrDetail(0,2)="赵六"
arrDetail(1,2)="25"

'Response.Write Ubound(arrDetail,2)&"<br/>"

With oJsonResponse.data
    if peopleId="zhangsan" then
    .Add "peopleId","zhangsan" 
        .Add "peopleName","张三"
        .Add "age","30"
        .Add "position","Manager" 
        .Add "subordinate",oJsonResponse.Collection()
        With .item("subordinate")
            indexI = 0
            for indexI=0 to Ubound(arrDetail,2)-1
                'Response.Write "indexI="&indexI&"<br/>"
                .Add indexI,oJsonResponse.Collection()
                With .item(indexI)
                    .Add "name",arrDetail(0,indexI)
                    .Add "age",arrDetail(1,indexI)  
                End With

                'indexI = indexI +1
            next
        End With
    end if

    if peopleId="lisi" then
    .Add "peopleId","lisi" 
        .Add "peopleName","李四"
        .Add "age","40"
        .Add "position","Manager" 
        .Add "subordinate",oJsonResponse.Collection()
        With .item("subordinate")
            indexI = 0
            for indexI=0 to Ubound(arrDetail,2)-1
                'Response.Write "indexI="&indexI&"<br/>"
                .Add indexI,oJsonResponse.Collection()
                With .item(indexI)
                    .Add "name",arrDetail(0,indexI)
                    .Add "age",arrDetail(1,indexI)  
                End With

                'indexI = indexI +1
            next
        End With
    end if
End With

Response.Write oJsonResponse.JSONoutput()
%>

java接口,部署在http://localhost:8082上

1、/login/getPeople1

@PostMapping("/getPeople1")
    @ResponseBody
    public PeopleDTO getPeople1(@RequestBody Map<String, Object> map) {
        String peopleId = map.get("PeopleId").toString();
        PeopleDTO peopleDTO1 = new PeopleDTO("zhangsan", "张三", "30", "Manager", null);
        PeopleDTO peopleDTO2 = new PeopleDTO("lisi", "李四", "40", "Manager", null);
        PeopleV2DTO peopleV2DTO1 = new PeopleV2DTO("李五", "20");
        PeopleV2DTO peopleV2DTO2 = new PeopleV2DTO("王五", "22");
        PeopleV2DTO peopleV2DTO3 = new PeopleV2DTO("赵六", "25");
        List<PeopleV2DTO> peopleV2DTOList = Arrays.asList(peopleV2DTO1, peopleV2DTO2, peopleV2DTO3);
        peopleDTO1.setSubordinate(peopleV2DTOList);
        peopleDTO2.setSubordinate(peopleV2DTOList);
        if (peopleId.equals("zhangsan")) {
            return peopleDTO1;
        }
        if (peopleId.equals("lisi")) {
            return peopleDTO2;
        }
        return null;
    }

运行效果 

 

4、总结

        前端进行http请求后端接口可以有三个选择:ajax,axios和fetch。ajax普遍用于jquery中的。axios和fetch都是用于vue,react之类的前端主流框架。更推荐使用axios而不是fetch,因为fetch比较老,对浏览器的兼容性不如axios。并且由于fetch是偏向于底层原生的嘛。所以fetch所提供的功能不如axios强大。

axios与fetch比较可以参考一下这篇:Axios or fetch():你更中意哪一个? - 掘金 (juejin.cn)

简单概括一下 axios与fetch的差异:

  • axios对浏览器的兼容性比fetch更广。
  • axios的返回值可以自动转为json格式,但fetch会返回一个包含响应结果的promise,所以fetch需要手动使用json()方法进行一个转换。
  • axios在一些基础配置使用上,比如配置拦截器,配置响应超时时间,同时发起多个响应请求上要比fetch更加快捷方便。

        在实际使用axios过程中,都会倾向于先对axios进行一个封装。统一配置像baseURL、timeout、responseType、headers等等属性,以便于开箱即用。

        

5、参考资料

最新React使用 http-proxy-middleware解决多跨域问题(完美篇)_晴天小哥哥的博客-CSDN博客

创建react-ts项目(简易) - 掘金 

 yarn npm 设置淘宝镜像_AlbertGou的博客-CSDN博客

 路由 | UmiJS

package-lock.json found. Your project contains lock files generated by tools,yarn和npm一起使用了解决方式_warning package-lock.json found. your project cont_KAGHQ的博客-CSDN博客

TypeScript 与 JavaScript:你应该知道的区别 - 掘金 

java后台接收json数据_json对象,后端实体类怎么接_随影随行的博客-CSDN博客 

TypeScript中文网 · TypeScript——JavaScript的超集 

如何开始使用ts,又如何将ts编译成js - 掘金 

Axios or fetch():你更中意哪一个? - 掘金 

axios基本使用及封装 - 掘金 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/31953.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

如何清除浏览器的 DNS 缓存 (Chrome, Firefox, Safari)

如何清除浏览器的 DNS 缓存 (Chrome, Firefox, Safari) Chrome Chromium Edge Firefox Safari clear DNS Cache, flush DNS cache 请访问原文链接&#xff1a;https://sysin.org/blog/clear-browser-dns-cache/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。…

设计模型学习-UML图

1&#xff0c;简介 UML图有很多种类型&#xff0c;但掌握其中的类图、用例图和时序图就可以完成大部分的工作。其中最重要的便是「类图」&#xff0c;它是面向对象建模中最常用和最重要的图&#xff0c;是定义其他图的基础。 类图主要是用来显示系统中的类、接口以及它们之间的…

Qt/C++编写手机版本视频播放器和Onvif工具(可云台和录像)

一、前言 用Qtffmpeg写播放器很多人有疑问&#xff0c;为何不用Qt自己的多媒体框架来写&#xff0c;最重要的原因是Qt自带的目前都依赖具体的本地解码器&#xff0c;如果解码器不支持&#xff0c;那就是歇菜的&#xff0c;最多支持个MP4格式&#xff0c;而且在手机上也都是支持…

音视频数据处理-H265/HEVC视频码流分析

一、H265概述 H265/HEVC&#xff08;Hight Efficiency Video Coding&#xff09;是由ITU-T和ISO/IEC两大组织在H264/AVC的基础之上推出的新一代高效视频编码标准&#xff0c;主要为应对高清和超高清视频在网络传输和数据存储方面带来的挑战。上一篇文章对H264/AVC视频码流进行…

python复习第一章

什么是 Python&#xff1f; Python 是一门流行的编程语言。它由 Guido van Rossum 创建&#xff0c;于 1991 年发布。 它用于&#xff1a; Web 开发&#xff08;服务器端&#xff09;软件开发数学系统脚本 Python 可以做什么&#xff1f; 可以在服务器上使用 Python 来创建…

【软件设计师暴击考点】下午题高频考点暴击系列

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;软件…

“前端已死”

一、一些迹象 逛社区&#xff0c;偶然看到了这张图片&#xff1a; 嗯……我眉头一皱&#xff0c;久久不语&#xff0c;心想&#xff0c;有这么夸张吗&#xff0c;假的吧&#xff1f; 突然想到&#xff0c;最近我在社区发了个前端招聘的信息&#xff0c;结果简历漫天纷飞&…

RK3568平台开发系列讲解(外设篇)四线风扇驱动实验

🚀返回专栏总目录 文章目录 一、硬件连接二、原理图分析三、驱动适配3.1、内核配置3.2、修改设备树3.3、实验沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇我们将讲解四线风扇的使用。 一、硬件连接 风扇模块如下所示,黑线是负,红线是正,黄线是测速,蓝线是…

定时器的实现原理

文章目录 1.定时器的作用?2.数据结构要求3.时间轮4.分级时间轮5.业界实现方案参考文献 1.定时器的作用? 定时器的主要用途是执行定时任务。 定时任务在很多场景都需要用到&#xff0c;比如游戏的 Buff 实现&#xff0c;Redis 中的过期任务&#xff0c;Linux 中的定时任务&a…

【总结】yarn ResourceManager 宕机重启总是失败解决排查

目录 Yarn ResourceManager 莫名奇妙宕机重启Yarn ResourceManager 报错1重启Yarn ResourceManager 报错2成功解决 Yarn ResourceManager 莫名奇妙宕机 接到同事反馈&#xff0c;说yarn RM 端口总是访问超时。但是查看日志&#xff0c;又没有发现任务蛛丝马迹&#xff0c;且RM…

Redis的复制

配置 在Redis中使用复制功能非常容易 在从Redis服务器的redis.conf中写入slaveof masterip masterport即可&#xff0c;主Redis服务器不需要做任何配置在启动Redis服务器的时候&#xff0c;指定主服务器&#xff0c;redis-server --slaveof masterip masterport在客户端指定主…

如何评估大型语言模型(LLM)?

编者按&#xff1a;近期几乎每隔一段时间&#xff0c;就有新的大语言模型发布&#xff0c;但是当下仍然没有一个通用的标准来评估这些大型语言模型的质量&#xff0c;我们急需一个可靠的、综合的LLM评估框架。 本文说明了为什么我们需要一个全面的大模型评估框架&#xff0c;并…

C#TryCatch用法

前几天一个学员在学习C#与TryCatch用法时,也不知道TryCatch用法装可以用来做什么 。下面我们就详细讲讲C# 和封TryCatch用法相关知识。 C# 是一种通用、类型安全且面向对象的编程语言&#xff0c;由微软开发并在 .NET 平台上运行。TryCatch 是 C# 语言中的一个结构&#xff0c…

CSS的自定义属性var和JS的classList.toggle()方法,使用详细(css中var变量怎么应用)

简介&#xff1a;CSS中的var&#xff08;变量&#xff09;是CSS3中的新特性&#xff0c;用于定义可重用的值&#xff0c;类似于编程语言中的变量&#xff1b;它允许您在整个CSS文件中定义一个值&#xff0c;并在需要时使用该值。这样可以使CSS更加灵活和易于维护&#xff1b;cl…

环境搭建【1】VM和ubuntun 环境搭建

1.安装VMware 1.1 下载安装包 &#xff08;1&#xff09;官网下载&#xff1a;https://customerconnect.vmware.com/en/downloads/info/slug/desktop_end_user_computing/vmware_workstation_pro/16_0 &#xff08;2&#xff09;百度网盘&#xff1a;https://pan.baidu.com/s/…

软考高级系统架构设计师(三) 基础知识之操作系统2(分页/分段/段页存储)

目录 存储管理 页式存储 段式存储 段页式存储 存储管理 存储管理的主要目的&#xff1a;解决多个用户共同使用主存的问题&#xff08;怎么分配内存&#xff1f;&#xff1f;&#xff09; 主要包括分区存储管理、分页存储管理、分段存储器管理、段页式存储管理以及虚拟存储…

windows10企业版安装西门子博途V15---01准备环境

网上看到了很多博途安装的文章或视频&#xff0c;一大部分都是你抄抄&#xff0c;我抄抄&#xff0c;滥鱼充饥&#xff0c;一是文章思路不清晰&#xff0c;二是具体安装环境不一致&#xff0c;三是视频讲解混乱&#xff0c;视频不清楚&#xff0c;操作有错误&#xff0c;其中不…

2022(一等奖)D678基于改进结构函数法的大气气溶胶遥感反演

作品介绍 1 应用背景 大气气溶胶是大气中重要的成分之一&#xff0c;是悬浮于大气中的固体和液体微粒与它们的气体载体共同组成的多相体系&#xff0c;其尺度大约在10-3到102 μm之间。大气气溶胶的特性对空气质量具有良好的指示作用&#xff0c;气溶胶的研究对空气质量的监测…

使用大白菜PE给苹果电脑安装win7ghost

如何安装大白菜苹果电脑&#xff1f;ghost (苹果电脑能用大白菜安装系统吗) 喜欢用苹果Mac电脑&#xff0c;开始后发现不习惯苹果的操作系统&#xff0c;还是习惯用Windows我们可以给苹果系统Mac电脑上安装Windows系统&#xff0c;享受苹果的外观&#xff0c;操作windows系统…

机器学习之基于LDA的人脸识别

目录 LDA降维 思想 matlab代码 fisherface 思想 matlab代码 人脸识别 思想 matlab代码 LDA降维 思想 首先&#xff0c;代码通过使用dir函数获取指定路径下所有以".bmp"结尾的文件&#xff0c;并存储在变量pictures中。 然后&#xff0c;定义了一些参数&a…