理解
1)前置说明
React本身只关注界面,并不包含发送ajax请求的代码 前端应用需要通过ajax请求与后端进行json
交互react应用中需要集成第三方ajax库(或者是自己封装)
2)常用的ajax请求库
jQuery:比较重,如果需要另外引入,不建议使用
axios:轻量级,建议使用 封装XMLHttpRequest对象的ajax promise风格 可以用在浏览器和node服
务器 注意:因为要使用到axios,所以第一步是先进行axios的安装:npm i axios;另外,在哪个组
件需 要使用aixos发送请求,就要在该文件引入axios(import axios from 'axios')
配置反向代理
方法一
import React, { Component } from 'react'
import axios from 'axios'
export default class App extends Component {
getStudentData = () => {
axios.get('http://localhost:3000/students').then(
response => {console.log('成功了', response.data);},
error => {console.log('失败了',error.message);}
)
}
getCarsData = () => {
axios.get('http://localhost:3000/cars').then(
response => {console.log('成功了', response.data);},
error => {console.log('失败了',error.message);}
)
}
render() {
return (
<div>
<button onClick= {this.getStudentData}>点击获取学习信息</button>
<button onClick= {this.getCarsData}>点击获取汽车信息</button>
</div>
)
}
}
在package.json中做代理配置:
"proxy": "http://localhost:5000"
//与其他的配置对象是兄弟关系
说明:因为本地服务器是http://localhost:3000,发送请求从另一个服务(http://localhost:5000/stu
dent)获 取数据,出现了跨域,所以进行了反向代理,使用该方法的缺陷是只能配置一个代理,
而且只能是3000服务器没 有的才找5000服务器
方法二
第一步:创建代理文件
在src下创建代理文件:src/setupProxy.js(不许更改名字)
第二步:在setupProxy.js中写配置文件
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(
proxy('/api1', {//遇见api1前缀的请求,就会触发该代理配置
target: 'http://localhost:5000', //请求转发给谁
changeOrigin: true, //控制服务器收到的请求头的host字段
pathRewrite:{'^/api1': ''}//重写请求路径(必写)
}),
proxy('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite:{'^/api2': ''}
})
)
}
第三步:使用
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.message);}
)
}
getCarsData = () => {
axios.get('http://localhost:3000/api2/cars').then(
response => {console.log('成功了', response.data);},
error => {console.log('失败了',error.message);}
)
}
render() {
return (
<div>
<button onClick= {this.getStudentData}>点击获取学习信息</button>
<button onClick= {this.getCarsData}>点击获取汽车信息</button>
</div>
)
}
}
说明:
1.优点:可以配置多个代理,可以灵活的控制是否走代理
2.缺点:配置繁琐,前端请求资源时必须写前缀