1.ajax请求
React本身并不包含发送ajax请求的代码,需要自己引入一个第三方库
不推荐使用jQuery,因为它比较重,而且使用js操作DOM,在React中我们不推荐这样
这里推荐轻量级框架axios
npm i axios
2. 简单模拟ajax请求
①客户端 --- React
客户端页面所在地址为本机地址,端口为3000
/client/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<title>Hello</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
/client/src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App' //引入App组件
//渲染App到页面
ReactDOM.render(<App/>,document.getElementById('root'));
/client/src/App.js
import React,{Component} from 'react'
import axios from 'axios'
export default class App extends Component{
getStudentData = ()=>{
axios.get('http://localhost:3000/api1/students').then(
response => {console.log('成功',response.data)},
error => {console.log('失败',error);}
)
}
getCarData = ()=>{
axios.get('http://localhost:3000/api1/cars').then(
response => {console.log('成功',response.data)},
error => {console.log('失败',error);}
)
}
render(){
return (
<div>
<button onClick={this.getStudentData}>获取学生数据</button>
<button onClick={this.getCarData}>获取汽车数据</button>
</div>
)
}
}
②服务器端 --- Node + Express
在本机模拟了两台服务器,分别监听端口5000和5001,开启服务:
node server1.js
node server2.js
/server/server1.js
const express = require('express')
const app = express()
app.use((req,res,next)=>{
console.log('有人请求服务器1了')
next()
})
app.use('/students',(req,res)=>{
const students = [
{id:'001',name:'Tom',age:18},
{id:'002',name:'Nancy',age:19},
{id:'003',name:'John',age:20},
]
res.send(students)
})
app.listen(5000,err=>{
if(!err) console.log('服务器1启动成功,监听端口为5000...')
})
/server/server2.js
const express = require('express')
const app = express()
app.use((req,res,next)=>{
console.log('有人请求服务器2了')
next()
})
app.use('/cars',(req,res)=>{
const cars = [
{id:'001',name:'奔驰',price:199},
{id:'002',name:'马自达',age:109},
{id:'003',name:'捷达',age:120},
]
res.send(cars)
})
app.listen(5001,err=>{
if(!err) console.log('服务器2启动成功,监听端口为5001...')
})
3.解决跨域问题
①方法一
在/client/src/package.json中追加如下配置
"proxy":"http://localhost:5000"
缺点:不能配置多个代理
工作方式:按上述方式配置代理,当请求了3000端口不存在的资源时,才会将该请求转发给5000(优先匹配前端资源)
②方法二
创建代理配置文件:/client/src/setupProxy.js