React封装axios请求

news2024/9/22 19:43:05

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.coloradmin.cn/o/673520.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于座位预约管理系统的设计与实现

前言&#xff1a; 各位小伙伴儿们端午节快乐&#xff0c;本篇文章为大家带来一份基于ssm技术搭建的项目&#xff0c;正在学习这块技术的童靴们可以体验一下哦&#xff0c;在资源中可获取源码 ~ 以下正文开始&#xff1a; 文章目录 需求分析功能模块项目架构图首页部分Controll…

存储笔记 - 整理

文章目录 第一章 存储系统introlesson 1何为数据&#xff1f;类型与关系 lesson 2 存储系统环境lesson 1lesson 2 Disk Drive 数据保护 RAIDlesson 1 智能存储lesson 第二章 存储网络技术与虚拟化DAS 直连式存储与 SCSIlesson 直连存储lesson&#xff1a; SCSI简介summary SANl…

长尾关键词有什么作用?要怎么用?

长尾关键词很多的网站都会忽略其存在&#xff0c;其实你不要小看长尾关键词&#xff0c;他将带给网站的流量也是极其可观的&#xff0c;所说比不上那些重点关键词的流量&#xff0c;但是对提升网站的权重还是有着重要的作用。 长尾关键词有什么用&#xff1f;长尾关键词的3…

基于spss的多元统计分析 之 因子分析(4/8)

实验目的&#xff1a; 1&#xff0e;掌握因子分析的基本思想&#xff1b; 2&#xff0e;熟悉掌握SPSS软件进行因子分析的基本操作&#xff1b; 3&#xff0e;利用实验指导的实例数据&#xff0c;上机熟悉因子分析方法。 实验内容&#xff1a; 附表的数据来自一次对液晶电视的调…

English Learning - L3 作业打卡 Lesson7 Day48 2023.6.21 周三

English Learning - L3 作业打卡 Lesson7 Day48 2023.6.21 周三 引言&#x1f349;句1: I thought the worst was over until weeks later when I saw my new legs for the first time.成分划分弱读连读爆破语调 &#x1f349;句2: I didn’t know what to expect but I wasn‘…

【C++】 Qt-认识Qt

文章目录 Qt简介Qt建立工程准备建立控制台程序建立桌面窗口程序 Qt简介 Qt&#xff08;官方发音[kju:t]&#xff0c;同音cute&#xff09;是一个跨平台的C开发库&#xff0c;主要用来开发图形用户界面&#xff08;Graphical User Interface&#xff0c;GUI&#xff09;程序&am…

Android之 日历单选多选控件

一&#xff0c;效果图 1.1 单选 2.2 多选 二 实现思路 2.1 数据来源&#xff0c;利用原生日历Calendar&#xff0c;获取从本月开始的往后一年的日期&#xff0c;遍历月数添加全部天数据 private void initCalendarData() {Calendar calendar Calendar.getInstance();year …

Chrome(Manifest Version 3) 浏览器扩展插件基础教程

文章目录 一、简介二、核心介绍三、自定义页面背景色三、设置页面背景图&#xff08;web_accessible_resources&#xff09;四、设置徽章&#xff08;Badge&#xff09;五、桌面通知六、消息通信七、自定义右键菜单&#xff08;添加、更新、删除&#xff09;八、Omnibox九、浏览…

网安笔记--整合

文章目录 1 intro威胁因素 2 加密密码体制分类安全性 3 DESDES工作模式多重DES和安全性加密策略 4 RSA PKCS保密系统体制分类单向函数用处 RSAElgamal 5 SHAHASHSHA-1SHA-2 6 数字签名基本概念签名体系MAC 消息认证码 7 密码协议协议距离协议分类密钥建立协议认证建立协议认证的…

云原生监控平台 Prometheus 的相关概念及部署

1 Prometheus简介 Prometheus 是一个开源的系统监控和报警系统&#xff0c;在 2012 年由 SoundCloud 公司创建&#xff0c;并于 2015 年正式发布。2016 年&#xff0c;Prometheus 正式加入 CNCF (Cloud Native Computing Foundation)&#xff0c;成为继kubernetes之后第二个在C…

Redis---集群

目录 一、集群的介绍 1.1 为什么需要集群呢&#xff1f; 1.2 什么是集群&#xff1f; 1.2 集群能干什么呢&#xff1f; 二、集群的算法之分片&槽位slot 2.1 什么是槽位slot&#xff1f; 2.2 分片 2.3 使用槽位和分片的优势 2.4 slot 槽位映射的三种算法 1、哈…

postgresql 从应用角度看快照snapshot使用,事务隔离控制不再神密

​专栏内容&#xff1a;postgresql内核源码分析 个人主页&#xff1a;我的主页 座右铭&#xff1a;天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物. 快照使用 快照是事务中使用&#xff0c;配合事务的隔离级别&#xff0c;体现出不同的可见性。…

端午节粽子(python)

目录 前言 正文 粽叶绘制 粽叶绳绘制 祝福语绘制 源代码 总结 前言 今天端午节&#xff0c;然后昨天也学习一下绘图的相关知识&#xff0c;然后就想看一下能不能画一下&#xff0c;结果还是有点困难的&#xff0c;用CharAI生成简直一言难尽了。后面是找了一个改了一下。 …

MicroBlaze Processor hello world实验

MicroBlaze Processor hello world实验 实验目的 搭建microblaze工程&#xff0c;通过串口打印hello world&#xff0c;了解microblaze的使用&#xff0c;加深对FPGA硬件和软件开发的理解。 实验原理 MicroBlaze Processor是xilinx提供的一个软核处理器&#xff08;使用FPGA…

Delta型腿机器狗全动作展示

1. 功能说明 本文示例将实现R322样机Delta型腿机器狗维持身体平衡、原地圆形摆动、原地踏步、蹲起、站立、前进、后退、转向、横向移动、斜向移动等功能。 2. 电子硬件 本实验中采用了以下硬件&#xff1a; 主控板 Basra主控板&#xff08;兼容Arduino Uno&#xff09;‍ 扩展…

追寻技术巅峰:开发者的端午征途

近年来&#xff0c;随着信息技术的飞速发展&#xff0c;开发者们以前所未有的速度和规模推动着技术的进步。而正如端午节的文化内涵所体现的那样&#xff0c;我们以屈原名言为指引&#xff0c;勉励着广大开发者在技术征途上不断追求极致&#xff0c;勇往直前。 一、端午节与技术…

macOS Sonoma 14 beta 2 (23A5276g) Boot ISO 原版可引导镜像

macOS Sonoma 14 beta 2 (23A5276g) Boot ISO 原版可引导镜像 本站下载的 macOS 软件包&#xff0c;既可以拖拽到 Applications&#xff08;应用程序&#xff09;下直接安装&#xff0c;也可以制作启动 U 盘安装&#xff0c;或者在虚拟机中启动安装。另外也支持在 Windows 和 …

【Flume】高级组件之Sink Processors及项目实践(Sink负载均衡和故障转移)

文章目录 1. 组件简介2. 项目实践2.1 负载均衡2.1.1 需求2.1.2 配置2.1.3 运行 2.2 故障转移2.2.1 需求2.2.2 配置2.2.3 运行 1. 组件简介 Sink Processors类型包括这三种&#xff1a;Default Sink Processor、Load balancing Sink Processor和Failover Sink Processor。 Defa…

AIGC连续内容生成几种方案

背景 从AI可以画图到现在各家都在功课的连续性内容的输出&#xff0c;正在AI画图进入到大众圈其实也不过1年左右时间。对于单图的研究已经逐渐完善&#xff0c;单图理论上讲&#xff0c;只要你能按要求做promt的设计出图率应该是比较高的。但是对于要生成连续的图或者要生成连…

推荐 5 个 火火火 的 GitHub 项目

推荐 5 个开源项目&#xff0c;前两个是 AI 相关&#xff0c;后面 3 个为逛逛GitHub 的读者推荐&#xff0c;如果你挖掘到了很棒的开源项目&#xff0c;可以给老逛投稿。 本期推荐开源项目目录&#xff1a; 1. SuperAGI&#xff08;AI&#xff09; 2. 一键换脸&#xff08;AI&a…