一、基础说明
前置说明
- React本身只关注于界面, 并不包含发送ajax请求的代码
- 前端应用需要通过ajax请求与后台进行交互(json数据)
- react应用中需要集成第三方ajax库(或自己封装)
常用的ajax请求库
- jQuery: 比较重, 如果需要另外引入,不建议使用。react的核心就是减少dom操作,仅操作数据,然后更新到dom。jquery库大,比较重,且主要来操作dom,故不适用react中。
- axios: 轻量级, 建议使用。可以专门学习这个课程
(1)封装XmlHttpRequest对象的ajax
(2)可以用在浏览器端和node服务器端
(3)promise风格
引入JS库
yarn为Facebook自己研发的包管理器,react也是fb开发,推荐使用yarn,yarn和npm都是js包管理工具;如下为yarn npm安装axios。
yarn add axios npm i axios
第三方安装的JS库,项目中直接引入即可
import React from ‘react’
自己写的js库引入时需要指定具体的js位置
import MyComponent from './componnets/MyComponent'
二、react解决跨域问题
为了更好的演示跨域问题,下面使用nodejs建立了服务端程序。
1. 搭建服务端
nodejs的express框架搭建服务端软件,用来接受请求 。node server.js 即可运行
const express = require('express') const app = express() app.use((request,response,next)=>{ console.log('有人请求服务器1了'); console.log('请求来自于',request.get('Host')); console.log('请求的地址',request.url); next() }) app.get('/students',(request,response)=>{ const students = [ {id:'001',name:'tom',age:18}, {id:'002',name:'jerry',age:19}, {id:'003',name:'tony',age:120}, ] response.send(students) }) app.listen(5000,(err)=>{ if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students'); })
2. react程序使用axios发送请求
如下会报错跨域。数据可以发送给服务端,服务端返回的数据回不到客户端,因为客户端有ajax的同源策略限制。
下面程序默认运行在localhost:3000端口
import React, { Component } from 'react' import axios from 'axios' export default class App extends Component { getStudentsInfo = () => { axios.get('http://localhost:5000/students').then( rsp => { console.log('收到数据', rsp) }, error => { console.log('错误', error) } ) } render() { return ( <button onClick={this.getStudentsInfo}>点我获取学生信息</button> ) } }
3.axios发送get请求和post请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
4.react脚手架配置代理解决跨域
本机不同端口发送数据,也会因为ajax同源策略限制导致跨域问题。不同ip或不同port就会产生跨域问题。
使用代理解决,代理运行在和react发送请求的客户端同一个端口,而且代理没有ajax同源策略限制,所以可以接受服务端返回数据,又因为和客户端同一个端口,所以客户端也可以接收到代理发回的数据。
react程序(端口3000)--->代理(为了解决跨域,端口必须和react一样,所以也是3000)--->服务端端口(可能是其他IP、其他端口)
方法一 前端使用代理解决跨域
(1)第一种方法
在package.json中添加如下配置
{ "proxy":"http://192.168.41.119:8086", "name": "xcdc2", "dependencies": { }, ... }
说明:
- )优点:配置简单,前端请求资源时可以不加任何前缀。
- )缺点:不能配置多个代理。
- )工作方式:上述方式配置代理,当前端程序发起了请求,发现请求的不是笨前端程序自身的静态资源时,那么该请求会转发给5000 (优先匹配前端资源)
- )proxy指定要请求的接口地址,前端程序中访问接口时不需要再写 http://ip:port。例如:本示例程序运行在3000端口,要访问localhost:5000的服务端接口,所以proxy写http://localhost:5000。如果请求地址是其他的,就写其他的具体请求地址。
(2)第二种方法
1. 创建代理配置文件
在src下创建配置文件:src/setupProxy.js
2. 编写setupProxy.js配置具体代理规则:
const proxy = require('http-proxy-middleware') module.exports = function(app) { app.use( proxy('/api1', { //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000) target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址) changeOrigin: true, //控制服务器接收到的请求头中host字段的值 /* changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000 changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000 changeOrigin默认值为false,但我们一般将changeOrigin值设为true */ pathRewrite: {'^/api1': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置) }), proxy('/api2', { target: 'http://localhost:5001', changeOrigin: true, pathRewrite: {'^/api2': ''} }) ) } ```
说明:
1. )优点:可以配置多个代理,可以灵活的控制请求是否走代理。
2. )缺点:配置繁琐,前端请求资源时必须加前缀。
3. 代理后,react程序请求的地址为代理所在的端口和代理映射路径
小技巧:配置代理后,axios相当于给本机的react使用的端口发请求,然后代理给实际的地址(自己给自己的端口发请求)。那么axios请求中的url http://localhost:port/部分可以省略不写,axios会自动发到本react程序运行的端口。
import React, { Component } from 'react' import axios from 'axios' export default class App extends Component { getStudentsInfo = () => { axios.get('http://localhost:3000/api1/students').then( rsp => { console.log('收到数据', rsp) }, error => { console.log('错误', error) } ) } //http://localhost:3000/api2/cars 可简写为/api2/cars //localhost:3000代理所在端口 api2为setupProxy配置的映射路径。 getCarsInfo = () => { axios.get('http://localhost:3000/api2/cars').then( rsp => { console.log('收到数据', rsp) }, error => { console.log('错误', error) } ) } render() { return ( <div> <button onClick={this.getStudentsInfo}>点我获取学生信息</button> <button onClick={this.getCarsInfo}>点我获取车辆信息</button> </div> ) } }
方法二 服务器端配置cors响应头
在服务器端设置响应头的cors,允许跨域即可。
但这个方法允许所有资源访问,安全性不好。
Spring boot 添加跨域参考资料