React ajax

理解

前置说明

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

常用的ajax请求库

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

配置代理

方法一

在package.json中追加如下配置

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

说明:

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。
  2. 缺点:不能配置多个代理。
  3. 工作方式:上述方式配置代理,当请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)

方法二

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

    在src下创建配置文件:src/setupProxy.js
    
  2. 编写setupProxy.js配置具体代理规则:

    // 版本为0.x.x
    const proxy = require('http-proxy-middleware');
    // 版本为1.x.x
    const { createProxyMiddleware } = require('http-proxy-middleware');
    // 下面的proxy方法同样要用createProxyMiddleware代替
    
    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. 缺点:配置繁琐,前端请求资源时必须加前缀。

axios

文档

https://axios-http.com/docs/intro

安装

npm install axios

引入

import axios from 'axios';

使用

get请求

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请求

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

消息订阅-发布机制

使用

git仓库:https://github.com/mroderick/PubSubJS

  • 工具库: PubSubJS
  • 下载: npm install pubsub-js --save
  • 使用:
    • import PubSub from 'pubsub-js' //引入
    • PubSub.subscribe('delete', function(data){ }); //订阅
    • PubSub.publish('delete', data) //发布消息

用途

可以用于任意组件间通信,一般用于兄弟组件间通信

componentDidMount() {
    // h第一个参数是消息名称,第二个是消息内容
    this.token = PubSub.subscribe('stateData', (_, newState) => {
        this.setState(
            newState
        )
    })
}

componentWillUnmount() {
    PubSub.unsubscribe(this.token);
}

fetch

文档

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

特点

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

使用

fetch(`/api1/search/users2?q=${keyword}`)
    .then(response => {
    	console.1og('联系服务器成功了');
    	return response.json()})
    .then(
    	response => { console.log('获取数据成功了',response);})
    .catch(
    	error =>{ console.log('请求出错',error); }
    )

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

fetch(url, {
    method: "POST",
    body: JSON.stringify(data),
}).then(function(data) {
    console.log(data)
}).catch(function(e) {
    console.log(e)
})
Last Updated:
Contributors: liushun-ing