react後端請求資料的實作方法:1、在package.json中設定「 "proxy":"http://localhost:5000"」;2、在src目錄下建立「setupProxy.js 」檔案;3、呼叫「setupProxy.js」中配置的功能,程式碼如「createProxyMiddleware('/api2',{target:...}」。
react-ajax
方法一:在package.json中設定
"proxy":"http://localhost:5000"
<pre class="brush:php;toolbar:false"> getStudentData = () => {
axios.get('/students').then(
(result) => { console.log(result.data); },
(reason) => { console.log(reason); })
}</pre>
#setupProxy.js
//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":""} }), )}
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> ) } }
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="react後端請求資料怎麼實現" > </a> <p>{item.login}</p> </div> })} </div> ) } }
var token=PubSub.subscribe("myTopic",myFunction[托管的函数])//token,是当前订阅函数的唯一id,可以用来取消订阅## ###########發佈者:發佈的意思是透過呼叫訂閱方指定的函數,實作傳參或執行操作功能#########
PubSub.publish('myTopic','需要发送给订阅者的内容')####### ###########第一步###:新增pubsub-js#########
yarn add pubsub-js#########**第二步:**在元件中導入#########
import PubSub from 'pubsub-js'#########**第三步:**呼叫PubSub訂閱函式(一般是在componentDidMount鉤子函式中訂閱)####### ###
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> ) } }#########發送ajax請求的方式有哪些? #########xhr:xmlHttpRequest:傳統的ajax######jQuery:封裝了xhr######axios:封裝了xhr############# **fetch(取)?*window內建的,不用借用第三方函式庫,直接使用######缺點:目前不是很好用,沒有要求發送攔截器########## ###########xhr######################fetch################ :相容性不高#########優點###:沒用xhr,不用安裝第三方函式庫,原生#################### ####fetch最佳寫法###
let getData=async()=>{ try{ let result=await fetch(url); let data=await result.json(); }catch(error){ console.log('请求错误',error) } }推薦學習:《###react影片教學###》 ##########
以上是react後端請求資料怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!