Table of Contents
##react-ajax" >##react-ajax
axios" >axios
Method 2: Create the setupProxy.js file in the src directory" >Method 2: Create the setupProxy.js file in the src directory
Cross-domain request real interface case" >Cross-domain request real interface case
搜索github用户
react-Communication between any components" > react-Communication between any components
Message subscription and publishing mechanism" >Message subscription and publishing mechanism
输入搜索内容搜索用户
Loading...
{err}
Home Web Front-end Front-end Q&A How to implement react backend request data

How to implement react backend request data

Dec 29, 2022 pm 01:48 PM
react

React backend request data implementation method: 1. Configure ""proxy":"http://localhost:5000"" in package.json; 2. Create "setupProxy.js" in the src directory " file; 3. Call the function configured in "setupProxy.js", the code is such as "createProxyMiddleware('/api2',{target:...}".

How to implement react backend request data

The operating environment of this tutorial: Windows 10 system, react version 18.0.0, Dell G3 computer.

How to request data from the react backend?

react -ajax request background data method

##react-ajax

axios

Method 1: Configure
 "proxy":"http://localhost:5000"
Copy after login

    in package.json so that localhost:5000 is the server we want to proxy to
  getStudentData = () => {
    axios.get('/students').then(
      (result) => { console.log(result.data); },
      (reason) => { console.log(reason); })
  }
Copy after login
    Get the data of /students in
  • localhost:5000
**Advantages: **Simple configuration, front-end request resources are not required Any prefix required

**Disadvantage: **Cannot configure multiple proxy servers

Method 2: Create the setupProxy.js file in the src directory

  • Step one: webpack is configured to call the function configured in setupProxy.js

  • setupProxy.js

  • Step 2: Configuration

//const proxy=require("http-proxy-middleware")   :视频中请求的包,引用它出现了无法访问的问题//应该使用以下写法*******const { createProxyMiddleware } = require("http-proxy-middleware");module.exports=function(app){
    app.use(
        createProxyMiddleware('/api1',{//遇见/api1前缀的请求,就会触发该代理配置
            target:"http://localhost:5000",//请求转发给谁
            changeOrigin:true,//控制服务器收到的请求头中Host字段的值:host就是主机名+端口号
            	//true:后端接收到的host:localhost:5000
            	//false:后端接收到的host:localhost:3000
            	//系统默认为false,一般会设为true
            pathRewrite:{"^/api1":""}//重写请求路径(必须要写)
            //不写:后台接收到的请求路径:/api1/student
            //写了:后台请求的路径:/student
        }),
        createProxyMiddleware('/api2',{
            target:"http://localhost:5001",
            changeOrigin:true,
            pathRewrite:{"^/api2":""}
        }),
    )}
Copy after login
  • Solution link: https://www.csdn.net/tags/OtTaIg0sNzE3OC1ibG9n.html

  • Cross-domain request real interface case

    • App.jsx

    import React, { Component } from 'react'
    import Search from './components/Search'
    import List from './components/List'
    import './App.css'
    
    export default class App extends Component {
    state={users:[]}
    getSearchResult=(result)=>{
      this.setState({users:result})
    }
    
      render() {
        return (
          <div>
            <search></search>
            <list></list>
          </div>
        )
      }
    }
    Copy after login
  • Search.jsx

  • import React, { Component } from 'react'
    import axios from 'axios'
    import './index.css'
    
    export default class Search extends Component {
    
      search = () => {
        //获取输入框中的值
        const { value } = this.keyWordElement;
        //发送请求
        axios.get(`/api1/search/users?q=${value}`).then(
          result => {
            this.props.getSearchResult(result.data.items)
          },
          reason => {
            console.log(reason);
          })
      }
    
    
    
      render() {
        return (
          <section>
            <h3 id="搜索github用户">搜索github用户</h3>
            <div>
              <input> this.keyWordElement = c} type="text" placeholder="enter the name you search" /> <button>搜索</button>
            </div>
          </section>
        )
      }
    }
    Copy after login
  • List.jsx

  • import React, { Component } from 'react'
    
    import './index.css'
    export default class List extends Component {
      render() {
        return (
          <div>
            {this.props.users.map(item=>{
                return    <div>
                    <a>
                      <img  src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/020/8311c35cd4729255aa36862f92c15493-0.png" class="lazy" alt="How to implement react backend request data" >
                    </a>
                    <p>{item.login}</p>
                  </div>
            })}
      
           
          </div>  
        )
      }
    }
    Copy after login

    react-Communication between any components

    Message subscription and publishing mechanism

    PubSubJs:

    ##pub:( publish) publish
    • sub:(subscribe) subscribe
    pubsub-js

    : It is used to implement publish and subscribe. You can see it in vue. eventBus, regarded as the carrier of the function

      Subscriber: Create a function and pass this function to pubsub for hosting
    • var token=PubSub.subscribe("myTopic",myFunction[托管的函数])//token,是当前订阅函数的唯一id,可以用来取消订阅
      Copy after login
    • Publisher: Publishing means to realize the function of passing parameters or performing operations by calling the function specified by the subscriber
    • PubSub.publish('myTopic','需要发送给订阅者的内容')
      Copy after login
    Step 1

    : Add pubsub-js

    yarn add pubsub-js
    Copy after login
    • **Step 2:**In Import

    import PubSub from 'pubsub-js'
    Copy after login
    • into the component **Step 3: **Call the PubSub subscription function (usually subscribed in the componentDidMount hook function)

      componentDidMount(){
        this.token=PubSub.subscribe("changeState",this.changeStateObj)
      }
    Copy after login

    demo

    List.jsx

    Search. jsx
    import React, { Component } from 'react'
    import axios from 'axios'
    import './index.css'
    import PubSub from 'pubsub-js'
    
    export default class Search extends Component {
      
    
      search = () => {
        //获取输入框中的值
        const { value } = this.keyWordElement;
        PubSub.publish('changeState',{isFirst:false,isLoading:true})
        //发送请求
        axios.get(`/api1/search/users2?q=${value}`).then(
          result => {
            PubSub.publish('changeState',{isLoading:false,users:result.data.items})
    
          },
          reason => {
            PubSub.publish('changeState',{isLoading:false,err:reason.message})
    
          })
      }
    
    
    
      render() {
        return (
          <section>
            <h3 id="搜索github用户">搜索github用户</h3>
            <div>
              <input> this.keyWordElement = c} type="text" placeholder="enter the name you search" /> <button>搜索</button>
            </div>
          </section>
        )
      }
    }
    Copy after login

    App.jsx
    import React, { Component } from 'react'
    import Search from './components/Search'
    import List from './components/List'
    import './App.css'
    
    export default class App extends Component {
    
    
    
      render() {
        return (
          <div>
            <search></search>
            <list></list>
          </div>
        )
      }
    }
    Copy after login

    What are the ways to send ajax requests?

    xhr:xmlHttpRequest: traditional ajax
    • jQuery: encapsulated xhr
      • axios: encapsulated xhr
      **fetch (fetch)?* Built-in in window, no need to borrow third-party libraries, use it directly
    • Disadvantages: It is not very useful at the moment, there is no request sending interceptor

    xhr

    How to implement react backend request data

    fetch

      Disadvantages
    • : Low compatibility
    • Advantages
    • : No need to use xhr, no need to install third-party libraries, native

    How to implement react backend request data

    ##The best way to write fetch

    let getData=async()=>{	
    	try{
            let result=await fetch(url);
            let data=await result.json();
        }catch(error){
            console.log('请求错误',error)
        }
    }
    Copy after login
    recommends learning: "react video tutorial"

    The above is the detailed content of How to implement react backend request data. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

    How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

    Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

    React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

    How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

    How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

    How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

    How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

    React responsive design guide: How to achieve adaptive front-end layout effects React responsive design guide: How to achieve adaptive front-end layout effects Sep 26, 2023 am 11:34 AM

    React Responsive Design Guide: How to Achieve Adaptive Front-end Layout Effects With the popularity of mobile devices and the increasing user demand for multi-screen experiences, responsive design has become one of the important considerations in modern front-end development. React, as one of the most popular front-end frameworks at present, provides a wealth of tools and components to help developers achieve adaptive layout effects. This article will share some guidelines and tips on implementing responsive design using React, and provide specific code examples for reference. Fle using React

    React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

    React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

    React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

    ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

    How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

    How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

    See all articles