React---Ajax相关(axios)、消息订阅/发布机制、fetch

332 阅读4分钟

理解

前置说明

  1. React本身只关注于界面, 并不包含发送ajax请求的代码

  2. 前端应用需要通过ajax请求与后台进行交互(json数据)

  3. react应用中需要集成第三方ajax库(或自己封装)

常用的ajax请求库

1、jQuery: 比较重, 如果需要另外引入不建议使用

2、axios: 轻量级, 建议使用

  • 封装XmlHttpRequest对象的ajax

  • promise风格

  • 可以用在浏览器端和node服务器端

axios

安装:npm i axios

详情请看:官方文档

相关API

  1. GET请求
axios
  .get("/user?ID=12345")
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

// 写法二
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });
  1. POST请求
axios
  .post("/user", {
    firstName: "Fred",
    lastName: "Flintstone",
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

React中配置代理解决跨域问题

配置代理方法

解决跨域问题,在React开启中间代理

在项目中的package.json中,最后加上一行"proxy": "http://loaclhost:5000" 写到端口号即可

然后重启脚手架

再次发送请求的时候就直接写自己的3000端口

3000端口有的资源直接请求3000端口的,3000端口没有的资源就请求代理设置的5000端口

"proxy":"http://localhost:5000"

说明:

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。

  2. 缺点:不能配置多个代理。

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

配置多个代理方法

配置多个代理,不在 package.json 配置

  1. 第一步:创建代理配置文件

在src下创建配置文件:src/setupProxy.js

  1. 第二步:编写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. 缺点:配置繁琐,前端请求资源时必须加前缀。

消息订阅与发布

通过使用消息订阅与发布可以进行任组件之间的通信

PubSubJS库

  • 详情请看:文档

  • 下载:npm i pubsub-js

  • 使用:

哪个组件需要数据就在哪个组件中订阅;

哪个组件需要传递数据就在哪个组件发布;

import PubSub from 'pubsub-js' //引入

//两个参数:
//  第一个是消息名
//  第二个是执行的函数,其也有两个参数:
//      第一个是消息名,第二个是传递过来的数据
//在组件渲染到页面时就订阅,即在componentDidMount()中订阅
//token类似于定时器中的定时器名字,可在组件卸载时取消订阅
const token = PubSub.subscribe('delete', function(_,data){ }); // 订阅

//两个参数:
//  第一个是消息名
//  第二个是传递的数据
PubSub.publish('delete', data) // 发布消息 携带数据

//取消订阅,参数是之前订阅时起的名字
PubSub.unsubscribe(token)

Fetch

文档:

  1. github.github.io/fetch/

  2. segmentfault.com/a/119000000…

特点:

  1. fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求

  2. 老版本浏览器可能不支持

相关API:

  • GET请求
fetch(url).then(function(response) {
    return response.json()
  }).then(function(data) {
    console.log(data)
  }).catch(function(e) {
    console.log(e)
  });
  • POST请求
fetch(url, {
    method"POST",
    bodyJSON.stringify(data),
  }).then(function(data) {
    console.log(data)
  }).catch(function(e) {
    console.log(e)
  })

例:

//发送网络请求---使用fetch发送(未优化)
search = () =>{
    fetch(`/api1/search/users2?q=${keyWord}`).then(
        response => {
           console.log('联系服务器成功了');
           return response.json()
        },
        error => {
           console.log('联系服务器失败了',error);
           return new Promise(()=>{})
        }
    ).then(
        response => {console.log('获取数据成功了',response);},
        error => {console.log('获取数据失败了',error);}
    )
}



//发送网络请求---使用fetch发送(优化)
search = async()=>{
    try {
        const response = await fetch(`/api1/search/users2?q=${keyWord}`)
        const data = await response.json()
        console.log(data);
    } catch (error) {
        console.log('请求出错',error);
    }
}

总结

1、设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办。

2、消息订阅与发布机制

  1. 先订阅,再发布(理解:有一种隔空对话的感觉)
  2. 适用于任意组件间通信
  3. 要在组件的componentWillUnmount中取消订阅

3、fetch发送请求(关注分离的设计思想)

async function Search(){
    try {
        const response= await fetch(`/api1/search/users2?q=${keyWord}`)
        const data = await response.json()
        console.log(data);
    } catch (error) {
        console.log('请求出错',error);
    }
}