React学习day8——react ajax

推荐react ajax链接
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://blog.csdn.net/ZYC88888/article/details/82531610
安装axios

yarn add axios

配置代理

1、在src下创建代理文件xx.js
2、编写xx.js配置具体代理规则

//配置代理,可配置多个代理
const proxy = require('http-proxy-middleware')
module.exports = function(app){
    app.use(
        proxy('/api1',{
            target:'http:localhost:5000',
            changeOrigin:true,
            pathRewrite:{'^/api':''}
        }),
        proxy('/api2',{
            trarget:'http://localhost:50001',
            changeOrigin:true,
            pathRewrite:{'^/api2':''}
        })
    )
}

App.js

import './App.css';

//创建外壳组件
import React,{Component} from 'react'
//创建并暴露App组件
export default class App extends Component {
    getStudentData=()=> {
        // eslint-disable-next-line no-undef
        axios.get('http://localhost:5000/api/studentnpm').then(
          response=>{console.log('成功了',response.data);},
          error => {console.log('失败了',error);}
        )
    };
    getTeacherData=()=> {
        // eslint-disable-next-line no-undef
        axios.get('http://localhost:5001/api2/studentnpm').then(
            response=>{console.log('成功了',response.data);},
            error => {console.log('失败了',error);}
        )
    };
    
  render() {
    return (
        <div >
            <button onClick={this.getStudentData}>点我获取学生数据</button>
            <button onClick={this.getTeacherData}>点我获取学生数据</button>
        </div>
    )
  }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值