第四章React_ajax

一、为什么要使用axios


 1. 相对于其他基于ajax封装的请求,axios更加的轻便

二、使用axios

import React from "react";
import axios from 'axios'
// 创建外壳组件App
export default class Hello extends React.Component {
  getStudentsData = ()=>{
    axios.get('http://localhost:3000/api1/students').then(res=>{
      console.log(res);
    })
  }
  getCarData = () =>{
    axios.get('http://localhost:3000/api2/cars').then(res=>{
      console.log(res);
    })
  }
  render(){
    return (
      <div>
        <button onClick={this.getStudentsData}>点我获取学生数据</button>
        <button onClick={this.getCarData}>点我获取汽车数据</button>
      </div>
    )
  }
}

三、React中解决跨域的两种方式

3-1、解决跨域的第一种方式

优点:简单
缺点:只能代理一台服务器


 1. 再packge.json文件最后面加上代理服务器
	这里的后台服务器的端口是5000,代理服务器就向5000端口发请求
	 "proxy":"http://localhost:5000"
 2. 发送请求的时候发送到本地项目运行的服务器上
	react项目是默认运行在3000端口的,这里发送请求的时候需要向3000端口发
	getStudentsData = ()=>{
	    axios.get('http://localhost:3000/students').then(res=>{
	      console.log(res);
	    })
	  }
 3. 

3-2、解决跨域的第二种方式


 1. src目录下面床加你一个setupProxy.js
 2. setupProxy.js中的配置
	const {createProxyMiddleware} = require('http-proxy-middleware')


module.exports = function(app){
    app.use(
        createProxyMiddleware('/api1',{//遇见api1前缀的请求,就会触发该代理
            target:'http://localhost:5000',//请求转发给谁
            changeOrigin:true,//控制服务器收到的响应头中host】字段的值
            pathRewrite:{'^/api1':''}
        }),
        createProxyMiddleware('/api2',{
            target:'http://localhost:5001',
            changeOrigin:true,
            pathRewrite:{'^/api2':''}
        })
    )
}

四、消息订阅与发布

4-1、安装

 npm install pubsub-js
 yarn add pubsub-js

4-2、使用

A组件

import PubSub from 'pubsub-js';
componentDidMount(){
    // 消息订阅
    PubSub.subscribe('lq',(_,data)=>{
      this.setState(data)
    })
  }

B组件

import PubSub from 'pubsub-js';
PubSub.publish('lq',{isFirst:false,isLoading:true})

4-3、总结


 1. 消息订阅与发布适用于各种组件之间的通信

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧郁火龙果

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值