React + 项目(从基础到实战) -- 第八期

ops/2024/9/23 16:15:04/

ajax 请求的搭建

  1. 引入mock
  2. AP接口设计
  3. AJAX 通讯

前置知识

  • HTTP 协议 , 前后端通讯的桥梁
  • API : XMLHttpRequest 和 fetch
  • 常用工具axios

mock__13">mock 引入

Mock.js (mockjs.com)

mockJS_16">使用 mockJS

  1. 前端代码中引入 mockJs
  2. 定义要模拟的路由 , 返回结果
  3. mockJs 劫持ajax请求(返回模拟的结果)
import Mock from 'mockjs'Mock.mock('/api/test', 'get', ()=>{return {code: 0,data: {name:"lxy text"}}})

使用fetch api 向后端发起请求

 useEffect(()=>{fetch('/api/test').then((res)=>{console.log("res = ",res)}).then((err)=>{console.log("err = ",err)})},[])

bug : 发现返回的数据不是我们模拟的
mockjs 劫持失败

在这里插入图片描述

因为mock JS 只能劫持XMLHttpRequest

使用axios(要先安装哦) axios中文文档|axios中文网 | axios (axios-js.com)

  axios.get('/api/test').then(function (response) {console.log(response.data.data);}).catch(function (error) {console.log(error);});

成功

在这里插入图片描述

总结

  1. 只能劫持XMLHttpRequest 不能劫持fetch ,有局限性
  2. 注意线上环境要注释掉,否则线上请求也被劫持

前端项目中不建议使用 mock JS

mock_JS_106">node JS + mock JS

mockJS 用于nodeJS服务端 , 使用它的Random能力

后端操作

  1. 初始化node 环境 npm init -y

  2. 安装mock JS

  3. 安装nodemon
    自定义启动命令
    在这里插入图片描述

  4. 安装 koa
    Koa (koajs) – 基于 Node.js 平台的下一代 web 开发框架 | Koajs 中文文档 (bootcss.com)

这里添加异步函数模拟请求响应的时间差

const Mock = require('mockjs');const Random = Mock.Random;module.exports = [{url: '/api/question/:id',method: 'get',response: () => {return {code: 200,data: {id: Random.id(),title: Random.ctitle()}}}},{url: '/api/question',method: 'post',response: () => {return {code: 200,data: {id: Random.id(),name: Random.cname(),}}}}]
  const Koa = require('koa');const Router = require('koa-router');const mockList = require('./mock/index');const app = new Koa();const router = new Router();//定义异步函数async function getRes(fn) {return new Promise(resolve => {setTimeout(() => {const res= fn()resolve(res)}, 2000)})}//注册 mock 路由mockList.forEach(item => {const {url , method , response} = item;router[method](url, async ctx => {// const res=response();//模拟网络请求的加载状态, 2Sconst res = await getRes(response);ctx.body = res;})})app.use(router.routes());app.listen(3001) // 监听的端口号

启动成功

localhost:3001/api/question/12

在这里插入图片描述

前端操作

  useEffect(()=>{// 跨域// > 前端地址:http://localhost:3000// > 后端地址:http://localhost:3001fetch('http://localhost:3001/api/test').then((res)=>{console.log("res = ",res)}).then((err)=>{console.log("err = ",err)})},[])

跨域
前端地址:http://localhost:5173
后端地址:http://localhost:3001

解决vite的跨域问题_vite解决跨域-CSDN博客

发现还是报错

在后端改

在这里插入图片描述

mock_310">在线mock平台

fast-mock y-api swagger

API 设计

用户API

  1. 登录
  2. 注册
  3. 获取用户信息

问卷api

  1. 创建问卷
  2. 获取单个问卷
  3. 更新问卷
  4. 删除问卷
  5. 查询问卷
  6. 复制问卷

使用Restful API

method: ,
path: ,
request body: ,
responde: ,

用户验证

JWT

统一返回格式

errno , data ,msg

实战

axios__346">配置axios 基本功能

  1. 创建axios实例
  2. 配置全局的拦截器
import { message } from "antd";import axios from "axios";//1.创建实例const instance = axios.create({baseURL: 'http://localhost:3001/api/',timeout: 1000,//等待一秒headers: {'X-Custom-Header': 'foobar'}});//2.添加请求拦截器instance.interceptors.request.use(function () {// 在发送请求之前做些什么console.log("我要发请求啦");}, function () {// 对请求错误做些什么console.log("请求错误啦");});//3.添加响应拦截器instance.interceptors.response.use(function (res) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么console.log("我收到响应啦");const resData = (res.data || {}) as ResType;const {errno,data,msg} = resData;if(errno !== 0){message.error(msg || "未知错误");}return data as any;}, function () {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么console.log("响应错误啦");});//定义类型type ResType={errno:number,data?:ResDataType,msg?:string}type ResDataType={[keu:string]: any //可以有任意值,只要key键是string类型}export default instance ;

axios_463">模拟axios请求

请求函数

import axios , {ResDataType} from "./axios"//获取单个问卷export async function getQuestinService(id: string): Promise<ResDataType>{const url=`/question/${id}`const data = ( await axios.get(url) ) as ResDataType;return data;}

使用

import React,{FC,useEffect} from 'react'import {useParams} from 'react-router-dom';//导入发起请求的函数import { getQuestinService } from '../../../services/question';const Edit : FC = ()=>{//获取携带的参数const {id = ''} = useParams();useEffect(()=>{getQuestinService(id);},[])return (<><h1>edit  {id}</h1>{/* http://localhost:5173/question/edit/20 */}</>)}export default Edit;

报错
TypeError: Cannot read properties of undefined (reading ‘cancelToken’)
TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)_cannot read properties of undefined (reading 'canc-CSDN博客

又报错

message: ‘timeout of 1000ms exceeded’

原来是前端设置了等待一秒,改一下

timeout: 1000 * 10,//等待10秒

页面添加loading效果

自定义

function useLoadQuestionData() {const {id = ''} =useParams()const [loading,setLoading] = useState(true)const [questionData,setQuestionData] = useState({})useEffect(()=>{async function fn(){const data = await getQuestinService(id)setQuestionData(data)setLoading(false)}fn()},[])return {loading,questionData}}

使用ahooks中的useRequest

  async function load(){const data = await getQuestinService(id)return data;}const {loading,data,error} =useRequest(load)return {loading,data,error}

useRequest 与 自定义发请求

自定义请求

  const[questionList,setQuestionList] = useState([])const [total ,setTotal] =useState(0)useEffect(()=>{async function fn(){//问卷列表数据模拟const data= await getQuestinListService()const {list=[],total=0} =datasetQuestionList(list)setTotal(total)}fn()},[])

使用useRequest

 const {data={},loading} = useRequest(getQuestinListService)const {list=[],total=0} = data

列表增加搜索hook

向后端发起请求的接口

//获取(搜索)问卷列表export async function getQuestinListService(opt:Partial<SearchType>): Promise<ResDataType>{const url='/question'const data = ( await axios.get(url,{params:opt}) ) as ResDataType;return data;}

在这里插入图片描述

自定义hook

import {LIST_SEARCH_PARAM_KEY} from "../constant/index";import {  useSearchParams } from "react-router-dom";import { useRequest } from "ahooks";//导入发起请求的函数import { getQuestinListService } from "../services/question";function useLoadQuestionData() {const [searchParams] = useSearchParams();async function load(){const keyword=searchParams.get(LIST_SEARCH_PARAM_KEY) || " "const data = await getQuestinListService({keyword});return data;}const {loading,data,error} =useRequest(load,{refreshDeps:[searchParams],//刷新的依赖项})return {loading,data,error}}export default useLoadQuestionData;

使用自定义hook重构list,Star,Trash页面,向后端发请求

发现星标页面并未实现真的搜索功能

在这里插入图片描述

因为后端是随机生成的

在这里插入图片描述

解决

在这里插入图片描述

在这里插入图片描述


http://www.ppmy.cn/ops/6027.html

相关文章

【ROS2笔记五】ROS2服务通信

5.ROS2服务通信 文章目录 5.ROS2服务通信5.1ROS2中的服务工具5.2 rclcpp实现服务通信5.2.1创建功能包和节点5.2.2服务端实现5.2.3客户端实现 Reference 服务通信也是ROS2中基本的通信方式&#xff0c;服务分为客户端和服务端&#xff0c;由客户端向服务端发送请求&#xff0c;然…

使用Python进行云计算:AWS、Azure、和Google Cloud的比较

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 使用Python进行云计算&#xff1a;AWS、Azure、和Google Cloud的比较 随着云计算的普及&am…

apache是什么

​Apache(音译为阿帕奇)是世界使用排名第一的Web服务器软件。它可以运行在几乎所有广泛使用的计算机平台上&#xff0c;由于其跨平台和安全性被广泛使用&#xff0c;是最流行的Web服务器端软件之一。它快速、可靠并且可通过简单的API扩充&#xff0c;将Perl/Python等解释器编译…

linux限权

shell命令以及运行原理 什么是shell命令&#xff1a; 将使用者的命令翻译给核心&#xff08;kernel&#xff09;处理。同时&#xff0c;将核心的处理结果翻译给使用者。 shell就相当于操作系统外的一层外壳 其实就是登录linux时的一个可执行程序&#xff08;进程&#xff09…

LeetCode刷题总结 | 图论3—并查集

并查集理论基础 1.背景 首先要知道并查集可以解决什么问题呢&#xff1f; 并查集常用来解决连通性问题。大白话就是当我们需要判断两个元素是否在同一个集合里的时候&#xff0c;我们就要想到用并查集。 并查集主要有两个功能&#xff1a; 将两个元素添加到一个集合中。判…

[论文笔记]Root Mean Square Layer Normalization

引言 今天带来论文Root Mean Square Layer Normalization的笔记&#xff0c;论文题目是均方根层归一化。 本篇工作提出了RMSNorm&#xff0c;认为可以省略重新居中步骤。 简介 层归一化对Transformer等模型非常重要&#xff0c;它可以帮助稳定训练并提升模型收敛性&#xf…

C++修炼之路之多态--多态的条件与例外,重载+重写+重定义

目录 前言 一&#xff1a;构成多态的条件及一些特殊情况&#xff08;前提是构成父子类&#xff09; 1.多态是在不同的继承关系的类对象&#xff0c;去调用同一函数&#xff0c;产生了不同的结果 2.两个条件 3.三同的两个例外 1.协变---返回值类型可以不同&#xff0c;但必…

深入了解 Gitea:轻量级的自托管 Git 服务

在软件开发和团队协作中&#xff0c;版本控制系统是不可或缺的工具。Git 是目前最流行的分布式版本控制系统之一&#xff0c;而 Gitea 则是基于 Git 的一个轻量级、自托管的 Git 服务。本文将介绍 Gitea 的特点、功能和使用方法&#xff0c;帮助读者更好地了解和使用这一工具。…