React-Ajax

47次阅读
没有评论

共计 2541 个字符,预计需要花费 7 分钟才能阅读完成。

前置说明

  1. React本身只关注于界面, 并不包含发送ajax请求的代码
  2. 前端应用需要通过ajax请求与后台进行交互(json数据)
  3. react应用中需要集成第三方ajax库(或自己封装)

常用的ajax请求库

  1. jQuery: 比较重, 如果需要另外引入不建议使用
  2. axios: 轻量级, 建议使用
    • 封装XmlHttpRequest对象的ajax
    • promise风格
    • 可以用在浏览器端和node服务器端

axios

axios 中文文档

相关API

  • GET 请求
// 可用 async await 修饰
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);
});
  • POST 请求
// 可用 async await 修饰
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

React 脚手架配置代理

配置一个代理

根目录 package.json 文件内新加节点 "proxy": "请求地址"

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。
  2. 缺点:不能配置多个代理。

工作方式:上述方式配置代理,当请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)

配置多个代理

在 src 目录下 新建 setupProxy.js 里面要用 CommentJS 的语法写

// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function(app) {
app.use(
createProxyMiddleware('/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': ''} // 去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
}),
createProxyMiddleware('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: {'^/api2': ''}
})
)
}
// axios.get('http://localhost:3000/api2/students')
// axios.get('http://localhost:3000/api2/cars')
  1. 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
  2. 缺点:配置繁琐,前端请求资源时必须加前缀。

消息订阅-发布机制

  1. 工具库: PubSubJS
  2. 下载: npm install pubsub-js --save
  3. 使用:
    • import PubSub from 'pubsub-js' 引入
    • PubSub.subscribe('delete', function(data){ }) 订阅
    • PubSub.publish('delete', data) 发布消息
// List 组件
componentDidMount() {
// 订阅消息
this.token = PubSub.subscribe('USERS', (msg, date) => {
this.setState(date)
})
}
// 卸载组件时清除订阅
componentWillUnmount() {
PubSub.unsubscribe(this.state.token)
}
// Search 组件
// 发布消息
PubSub.publish('USERS', {
users: response.data.items,
isLoading: false
})

扩展:Fetch

文档

https://github.github.io/fetch/
https://segmentfault.com/a/1190000003810652

特点

  1. fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
  2. 老版本浏览器可能不支持

相关API

  1. GET 请求
fetch(url).then(function(response) {
return response.json()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
})
fetch(url).then((response) => {
return response.json()
}).then((data) => {
console.log(data)
}).catch((e) => {
console.log(e)
})
  1. POST 请求
fetch(url, {
method: "POST",
body: JSON.stringify(data),
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
})

正文完
 0
qiaofugui.cn
版权声明:本站原创文章,由 qiaofugui.cn 于2024-05-21发表,共计2541字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码