React 全栈体系(七)

2023-09-15 22:50:16

第四章 React ajax

一、理解

1. 前置说明

  • React 本身只关注于界面, 并不包含发送 ajax 请求的代码
  • 前端应用需要通过 ajax 请求与后台进行交互(json 数据)
  • react 应用中需要集成第三方 ajax 库(或自己封装)

2. 常用的 ajax 请求库

  • jQuery: 比较重, 如果需要另外引入不建议使用
  • axios: 轻量级, 建议使用
    • 封装 XmlHttpRequest 对象的 ajax
    • promise 风格
    • 可以用在浏览器端和 node 服务器端

二、axios

1. 文档

  • https://github.com/axios/axios

2. 相关 API

2.1 GET 请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
2.2 POST 请求
axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

3. 代码(配置代理)

/* src/App.jsx */
import React, { Component } from 'react'
import axios from 'axios'

export default class App extends Component {

	getStudentData = ()=>{
		axios.get('http://localhost:3000/api1/students').then(
			response => {console.log('成功了',response.data);},
			error => {console.log('失败了',error);}
		)
	}

	getCarData = ()=>{
		axios.get('http://localhost:3000/api2/cars').then(
			response => {console.log('成功了',response.data);},
			error => {console.log('失败了',error);}
		)
	}

	render() {
		return (
			<div>
				<button onClick={this.getStudentData}>点我获取学生数据</button>
				<button onClick={this.getCarData}>点我获取汽车数据</button>
			</div>
		)
	}
}
/* src/index.js */
//引入react核心库
import React from 'react'
//引入ReactDOM
import ReactDOM from 'react-dom'
//引入App
import App from './App'

ReactDOM.render(<App/>,document.getElementById('root'))
/* src/setupProxy.js */
const proxy = require('http-proxy-middleware')

module.exports = function(app){
	app.use(
		proxy('/api1',{ //遇见/api1前缀的请求,就会触发该代理配置
			target:'http://localhost:5000', //请求转发给谁
			changeOrigin:true,//控制服务器收到的请求头中Host的值
			pathRewrite:{'^/api1':''} //重写请求路径(必须)
		}),
		proxy('/api2',{
			target:'http://localhost:5001',
			changeOrigin:true,
			pathRewrite:{'^/api2':''}
		}),
	)
}
3.1 方法一

在 package.json 中追加如下配置

"proxy":"http://localhost:5000"
  • 说明:
    • 优点:配置简单,前端请求资源时可以不加任何前缀。
    • 缺点:不能配置多个代理。
    • 工作方式:上述方式配置代理,当请求了 3000 不存在的资源时,那么该请求会转发给 5000 (优先匹配前端资源)
3.2 方法二
  • 创建代理配置文件

在 src 下创建配置文件:src/setupProxy.js

  • 编写 setupProxy.js 配置具体代理规则:
const proxy = require('http-proxy-middleware')

module.exports = function(app) {
  app.use(
    proxy('/api1', {  //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
      target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址)
      changeOrigin: true, //控制服务器接收到的请求头中host字段的值
      /*
      	changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
      	changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000
      	changeOrigin默认值为false,但我们一般将changeOrigin值设为true
      */
      pathRewrite: {'^/api1': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
    }),
    proxy('/api2', {
      target: 'http://localhost:5001',
      changeOrigin: true,
      pathRewrite: {'^/api2': ''}
    })
  )
}
  • 说明:
    • 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
    • 缺点:配置繁琐,前端请求资源时必须加前缀。

三、案例 – github 用户搜索

1. 效果

  • 请求地址: https://api.github.com/search/users?q=xxxxxx

在这里插入图片描述

请添加图片描述

2. 代码实现

请添加图片描述

2.1 静态页面
/* public/css/bootstrap.css */
...
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="stylesheet" href="./css/bootstrap.css">

    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
/* src/App.css */
.album {
    min-height: 50rem; /* Can be removed; just added for demo purposes */
    padding-top: 3rem;
    padding-bottom: 3rem;
    background-color: #f7f7f7;
  }

  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }
/* src/App.jsx */
import React, { Component } from 'react'
import './App.css'

export default class App extends Component {
  render() {
	return (
	    <div className="container">
    <section className="jumbotron">
      <h3 className="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" placeholder="enter the name you search"/>&nbsp;<button>Search</button>
      </div>
    </section>
    <div className="row">
      <div className="card">
        <a href="https://github.com/reactjs" target="_blank">
          <img src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/>
        </a>
        <p className="card-text">reactjs</p>
      </div>
      <div className="card">
        <a href="https://github.com/reactjs" target="_blank">
          <img src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/>
        </a>
        <p className="card-text">reactjs</p>
      </div>
      <div className="card">
        <a href="https://github.com/reactjs" target="_blank">
          <img src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/>
        </a>
        <p className="card-text">reactjs</p>
      </div>
      <div className="card">
        <a href="https://github.com/reactjs" target="_blank">
          <img src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/>
        </a>
        <p className="card-text">reactjs</p>
      </div>
      <div className="card">
        <a href="https://github.com/reactjs" target="_blank">
          <img src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/>
        </a>
        <p className="card-text">reactjs</p>
      </div>
    </div>
  </div>
	)
  }
}
/* src/index.js */
//引入react核心库
import React from 'react'
//引入ReactDOM
import ReactDOM from 'react-dom'
//引入App组件
import App from './App'

//渲染App到页面
ReactDOM.render(<App/>,document.getElementById('root'))
2.2 静态组件
2.2.1 List
/* src/components/List/index.jsx */
import React, { Component } from "react";
import "./index.css";

export default class List extends Component {
  render() {
    return (
      <div className="row">
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
            <img
              alt="head_portrait"
              src="https://avatars.githubusercontent.com/u/6412038?v=3"
              style={{ width: "100px" }}
            />
          </a>
          <p className="card-text">reactjs</p>
        </div>
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
            <img
              alt="head_portrait"
              src="https://avatars.githubusercontent.com/u/6412038?v=3"
              style={{ width: "100px" }}
            />
          </a>
          <p className="card-text">reactjs</p>
        </div>
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
            <img
              alt="head_portrait"
              src="https://avatars.githubusercontent.com/u/6412038?v=3"
              style={{ width: "100px" }}
            />
          </a>
          <p className="card-text">reactjs</p>
        </div>
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
            <img
              alt="head_portrait"
              src="https://avatars.githubusercontent.com/u/6412038?v=3"
              style={{ width: "100px" }}
            />
          </a>
          <p className="card-text">reactjs</p>
        </div>
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
            <img
              alt="head_portrait"
              src="https://avatars.githubusercontent.com/u/6412038?v=3"
              style={{ width: "100px" }}
            />
          </a>
          <p className="card-text">reactjs</p>
        </div>
      </div>
    );
  }
}
/* src/components/List/index.css */
.album {
  min-height: 50rem; /* Can be removed; just added for demo purposes */
  padding-top: 3rem;
  padding-bottom: 3rem;
  background-color: #f7f7f7;
}

.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
2.2.2 Search
/* src/components/Search/index.jsx */
import React, { Component } from "react";

export default class Search extends Component {
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input type="text" placeholder="enter the name you search" />
          &nbsp;<button>Search</button>
        </div>
      </section>
    );
  }
}
2.2.3 App
/* src/App.jsx */
import React, { Component } from "react";
import Search from "./components/Search";
import List from "./components/List";

export default class App extends Component {
  render() {
    return (
      <div className="container">
        <Search />
        <List />
      </div>
    );
  }
}
更多推荐

npm常用命令系统介绍

npm常用命令系统介绍npmhelpnpminitpackage.json文件package.json文件属性说明默认package.json文件--参数[-yes|-y]设置package.json中字段的默认值package-lock.json文件npm[config|c]设置源npm[install|i]可选参数

【最新面试问题记录持续更新,java,kotlin,android,flutter】

最近找工作,复习了下java相关的知识。发现已经对很多概念模糊了。记录一下。部分是往年面试题重新整理,部分是自己面试遇到的问题。持续更新中~目录java相关1.面向对象设计原则2.面向对象的特征是什么3.重载和重写4.基本数据类型5.装箱和拆箱6.final有什么作用7.String是基本类型吗,可以被继承吗8.Str

vuepress+gitee免费搭建个人博客(无保留版)

文章目录最终效果,一睹为快!一、工具选型二、什么是VuePress三、准备工作3.1node安装3.2Git安装3.3Gitee账号注册四、搭建步骤4.1初始化VuePress4.2安装VuePress4.3初始化目录4.4编写文章五、部署到Gitee5.1创建仓库5.2个人空间地址设置4.3推送本地博客项目到Gite

linux如何查看各个文件夹大小

本文将介绍两种方法来查看Linux系统中文件夹的大小。方法一:使用du命令du命令是Linux系统中用于估算文件和目录容量的工具。通过du命令,可以查看文件夹的大小并按照目录层次结构进行排序。要查看文件夹的大小,可以按照以下语法使用du命令:du[选项][目录]其中,选项可以根据需要进行调整。一些常用的选项包括:-h:

使用JavaScript实现无限滚动的方法

前言在网页设计中,无限滚动是一种常见的交互方式,用户可持续地加载更多内容而无需刷新页面,提高用户体验。本文将介绍如何运用JavaScript实现无限滚动的效果,使网页能够自动加载更多数据,减轻用户加载新页的负担,为用户提供更好的访问体验。原理理解无限滚动的原理无限滚动的原理是当用户滚动到页面底部时,自动加载更多内容。这

计算机视觉的应用15-图片旋转验证码的角度计算模型的应用,解决旋转图片矫正问题

大家好,我是微学AI,今天给大家介绍一下计算机视觉的应用15-图片旋转验证码的角度计算模型的应用,解决旋转图片矫正问题,在CV领域,图片旋转验证码的角度计算模型被广泛应用于解决旋转图片矫正问题,有效解决机器识别图片验证码的问题。旋转图片验证码常用于验证用户身份,但由于图片可能被以不同角度旋转,识别难度比较大。本文提出了

HTML+CSS+JavaScript 大学生网页设计制作作业实例代码 200套静态响应式前端网页模板(全网最全,建议收藏)

目录1.介绍2.这样的响应式页面这里有200套不同风格的1.介绍资源链接📚web前端期末大作业(200套)集合Web前端期末大作业通常是一个综合性的项目,旨在检验学生在HTML、CSS和JavaScript等前端技术方面的能力和理解。以下是一些可能的Web前端期末大作业的示例和介绍:网页类型举例📘响应式网站开发:学

【接口自动化测试】Eolink Apilkit 安装部署,支持 Windows、Mac、Linux 等系统

EolinkApikit有三种客户端,可以依据自己的情况选择。三种客户端的数据是共用的,因此可以随时切换不同的客户端。我们推荐使用新推出的ApikitPC客户端,PC端拥有线上产品所有的功能,并且针对本地测试、自动化测试以及使用体验等方面进行了强化,可以提供最佳的使用感受。建议对本地测试有需求的用户使用PC端,可满足更

全球公链进展| Metis 将成为完全去中心化的 L 2 网络;Circle在NEAR和Noble上推出原生 USDC

一周速览过去一周,明星项目动态如下:Gethv1.13.1修补程序已发布,修复区块生产等问题Metis计划年内成为完全去中心化的Layer2网络Sui主网已升级至V1.9.1版本Circle在NEAR和Noble上推出原生USDCPolygon发布关于2.0升级和POL代币迁移的三项提案CosmosHub已完成「Gai

权限提升数据库(基于MySQL的UDF,MOF,启动项提权)

获取数据库权限如何获取数据库的最高权限用户的密码,常用方法有这些网站存在高权限SQL注入点数据库的存储文件或备份文件网站应用源码中的数据库配置文件采用工具或脚本爆破网站存在高权限SQL注入点可以通过sqlmap拿到user表的账号密码,密码可能是MD5加密的。可以通过下面网站进行解密md5在线解密破解,md5解密加密(

Python自动化测试实战

接口自动化测试是指通过编写程序来模拟用户的行为,对接口进行自动化测试。Python是一种流行的编程语言,它在接口自动化测试中得到了广泛应用。下面详细介绍Python接口自动化测试实战。1、接口自动化测试框架在Python接口自动化测试中,我们可以使用很多开源的测试框架,例如unittest、pytest和nose等。这

热文推荐