Home  >  Article  >  Web Front-end  >  How to implement react backend request data

How to implement react backend request data

藏色散人
藏色散人Original
2022-12-29 13:48:303090browse

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"

    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); })
  }
    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":""}
        }),
    )}
  • 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>
        )
      }
    }
  • 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>搜索github用户</h3>
            <div>
              <input> this.keyWordElement = c} type="text" placeholder="enter the name you search" /> <button>搜索</button>
            </div>
          </section>
        )
      }
    }
  • 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  alt="How to implement react backend request data" >
                    </a>
                    <p>{item.login}</p>
                  </div>
            })}
      
           
          </div>  
        )
      }
    }

    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,可以用来取消订阅
    • Publisher: Publishing means to realize the function of passing parameters or performing operations by calling the function specified by the subscriber
    • PubSub.publish('myTopic','需要发送给订阅者的内容')
    Step 1

    : Add pubsub-js

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

    import PubSub from 'pubsub-js'
    • 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)
      }

    demo

    List.jsx
    import React, { Component } from 'react'
    import PubSub from 'pubsub-js'
    import './index.css'
    export default class List extends Component {
      state={
        users:[],//拿到的用户信息
        isFirst:true,//是否第一次访问
        isLoading:false,//是否正在加载
        err:"",//返回的错误信息
      
      }
    
      changeStateObj=(msg,value)=>{
        this.setState(value)
      }
    
      componentDidMount(){
        this.token=PubSub.subscribe("changeState",this.changeStateObj)
      }
      componentWillUnmount(){
        PubSub.unsubscribe(this.token)
      }
     
      render() {
        let {users,isFirst,isLoading,err}=this.state
        return (
            
        )
      }
    }

    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>搜索github用户</h3>
            <div>
              <input> this.keyWordElement = c} type="text" placeholder="enter the name you search" /> <button>搜索</button>
            </div>
          </section>
        )
      }
    }

    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>
        )
      }
    }

    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)
        }
    }
    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:
    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