React怎么配置多个代理实现数据请求返回
导读:本文共2560.5字符,通常情况下阅读需要9分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要:本文小编为大家详细介绍“React怎么配置多个代理实现数据请求返回”,内容详细,步骤清晰,细节处理妥当,希望这篇“React怎么配置多个代理实现数据请求返回”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。使用axios以及express框架进行数据传输react脚手架中src文件配置如下:App.js:设置两个按钮,点击第一个获取学生数据,点击第二个获取汽车数据,值得注意... ...
目录
(为您整理了一些要点),点击可以直达。本文小编为大家详细介绍“React怎么配置多个代理实现数据请求返回”,内容详细,步骤清晰,细节处理妥当,希望这篇“React怎么配置多个代理实现数据请求返回”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
使用axios以及express框架进行数据传输
react脚手架中src文件配置如下:
App.js:
设置两个按钮,点击第一个获取学生数据,点击第二个获取汽车数据,值得注意的是这两个数据源在不同的服务器中
importReact,{Component}from'react'importaxiosfrom"axios"exportdefaultclassAppextendsComponent{ 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> <buttononClick={this.getStudentData}>点我获取学生数据</button> <buttononClick={this.getCarData}>点我获取学生数据</button> </div> )}}
index.js:
脚手架入口文件
//入口文件//引入react核心库importReactfrom'react';//引入ReactDOMimportReactDOMfrom'react-dom/client'//引入App组件importAppfrom"./App"//importReactDOMfrom'react-dom/client'constroot=ReactDOM.createRoot(document.getElementById("root"))root.render(<App/>)
server1.js:
服务器1的代码包含学生数据
constexpress=require('express')constapp=express()app.use((request,response,next)=>{console.log("有人请求服务器1");next();})app.get('/students',(request,response)=>{conststudents=[{id:"001",name:"tom",age:18},{id:"002",name:"jerry",age:18},{id:"003",name:"tony",age:8},]response.send(students)})app.listen(5000,(err)=>{if(!err)console.log("服务器1启动成功,地址为http://localhost:5000/students")})
server2.js
服务器2的内容,包含汽车的数据
constexpress=require('express')constapp=express()app.use((request,response,next)=>{console.log("有人请求服务器2");next();})app.get('/cars',(request,response)=>{constcars=[{id:"001",name:"宝马",price:18},{id:"002",name:"奔驰",price:18},{id:"003",name:"保时捷",price:8},]response.send(cars)})app.listen(5001,(err)=>{if(!err)console.log("服务器2启动成功,地址为http://localhost:5001/cars")})
setupProxy.js:
分别配置不同的代理(b站尚硅谷视频里那种运行不出来,版本更新了,下面这种目前可以跑出来)
const{createProxyMiddleware}=require('http-proxy-middleware')module.exports=function(app){app.use(createProxyMiddleware('/api1',{//api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)target:'http://localhost:5000',//配置转发目标地址(能返回数据的服务器地址)changeOrigin:true,//控制服务器接收到的请求头中host字段的值pathRewrite:{'^/api1':''},//去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)}),createProxyMiddleware('/api2',{target:'http://localhost:5001',changeOrigin:true,pathRewrite:{'^/api2':''},}))}
运行
启动服务器1:
nodeserver1.js
启动服务器2:
nodeserver2.js
启动脚手架:
npmstart
访问页面
点击第一个按钮:
点击第二个按钮:
读到这里,这篇“React怎么配置多个代理实现数据请求返回”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
React怎么配置多个代理实现数据请求返回的详细内容,希望对您有所帮助,信息来源于网络。