【React】Ajax 相关 - axios - 配置代理解决跨域问题 -消息订阅/发布机制 - PubSubJS - Fetch - github用户搜索案例

本文介绍了在React中使用axios进行Ajax请求,包括配置代理解决跨域问题,以及React应用中实现github用户搜索的案例。同时,文章探讨了消息订阅/发布机制PubSubJS在组件通信中的应用,以及Fetch作为内置网络请求方法的特点和使用示例。
摘要由CSDN通过智能技术生成

1. 理解

之前也学习过ajax和axios,用法都是一样的,可以直接看这个笔记

【Ajax】HTTP相关问题-GET-POST-XHR使用-jQuery中的ajax-跨域-同源-jsonp-cors

【axios】使用json-server 搭建REST API - 使用axios - 自定义axios - 取消请求 - 拦截器

1.1. 前置说明

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

1.2. 常用的ajax请求库

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

2. axios

安装npm install axios
在这里插入图片描述

2.1. 文档

https://github.com/axios/axios

2.2. 相关API

更多细节可以参考这个笔记的内容
【axios】使用json-server 搭建REST API - 使用axios - 自定义axios - 取消请求 - 拦截器

3. React中配置代理解决跨域问题

3.1 配置代理方法

解决跨域问题,在React开启中间代理
在项目中的package.json中,最后加上一行"proxy": "http://loaclhost:5000" 写到端口号
然后重启脚手架
再次发送请求的时候就直接写自己的3000端口
3000端口有的资源直接请求3000端口的,3000端口没有的资源就请求代理设置的5000端口

在package.json中追加如下配置

"proxy":"http://localhost:5000"

说明:

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。
  2. 缺点:不能配置多个代理。
  3. 工作方式:上述方式配置代理,当请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)

3.2 配置多个代理方法

配置多个代理,不在 package.json 配置

  1. 第一步:创建代理配置文件
在src下创建配置文件:src/setupProxy.js
  1. 编写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': ''}
    })
  )
}

说明:

  1. 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
  2. 缺点:配置繁琐,前端请求资源时必须加前缀。

4. 案例—github用户搜索

之前用Vue也做过这个案例,可以对比着学习
【Vue】Ajax实战-demo3-GitHub用户查询-axios-pubsub

4.1 效果

请求地址: https://api.github.com/search/users?q=xxxxxx
在这里插入图片描述

4.2 React 实现

4.2.1 静态页面拆分实现

在这里插入图片描述

App.jsx
import React, {
    Component } from 'react'
import Search from './Search'
import Users from './Users'

export default class App extends Component {
   
  render() {
   
    return (
      <div className="container">
        <Search />
        <Users />
    </div>
    )
  }
}
Search/index.js
import React, {
    Component } from 'react'

export default class Search extends Component {
   
  render() {
   
    return (
      <section className="jumbotron">
      <h3 className="jumbotron-heading">搜索Github用户</h3>
      <div>
          <input type="text" placeholder="请输入你要搜索的用户名" />&nbsp;
          <button>搜索</button>
      </div>
      </section>
    )
  }
}
User/index.jsx
import React, {
    Component } from 'react'
import './index.css'

export default class Users extends Component {
   
  render() {
   
    return (
      <div className="row">
        <div className="card">
          <a rel="noreferrer" href="https://github.com/reactjs" target="_blank">
              <img alt="avatar" 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="avatar" 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="avatar" 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="avatar" 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="avatar" src="https://avatars.githubusercontent.com/u/6412038?v=3" style={
   {
    'width': '100px' }}/>
          </a>
          <p className="card-text">reactjs</p>
        </div>
      </div>
   
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值