react结合axios发起ajax请求

react结合axios发起ajax请求

在项目根目录运行:cnpm i axios -S;安装axios包

用于测试的API地址:

get 请求地址: http://www.movie123.com:8081/api/getlunbo
post请求地址: http://www.movie123.com:8081/api/post

新建src/components/testAxios.jsx

import React from 'react'

export default class testAxios extends React.Component {
 constructor(){
    super()
    
    // 组件私有数据
    this.state = {
        
    }
}

 render(){	
     return <div>
     	<button onClick={()=>this.getInfo()}></button>
        <button onClick={()=>this.postInfo()}></button>
     </div>
 }
 // 实例方法
 async getInfo() {
     const {data} = await this.$http('/api/getlunbo')
     console.log(data)
 }
 async cpostInfo() {
     const result = await this.$http.post('/api/post',{
         name: 'zs',
         age: 23
     })
     console.log(result)
 }
 
}

抽离全局配置文件globalConfig.js

  • 全局配置请求的URL根路径
  • 挂载 axios 之前,全局配置一下 transformRequest 参数即可。
    transformRequest 作用:就是在发起post请求之前,对要发送给服务器的数据,做一层包装转换
    function 中的data就是要发送给服务器的数据
import React from 'react'

import axios from 'axios'

// 全局配置请求的URL根路径
axios.defaults.baseURL = 'http://www.movie123.com:8081';

// 全局配置一下 transformRequest 参数
axios.defaults.transformRequest = [function(data,headers){
    const arr = []
    for(let key in data){
        arr.push(key + '=' + data[key])
    }
    return arr.join('&')
}]

React.Component.prototype.$http = axios

在index.js页面中:

全局配置axios从而让每个组件都能直接调用axios发起Ajax请求

class 关键字 底层 也是由 普通 function 构造函数来实现的,因此 class 只是个语法糖

在每个 用 class 关键字 创建的 组件,都可以直接调用this.$http来发起Ajax请求

import React from 'react'
import ReactDOM from 'react-dom'

// 导入 axios
import '@/globalConfig.js'

// 导入 testAxios  组件
import testAxios from '@/components/testAxios'


ReactDOM.render(<div>
    <testAxios></testAxios>
</div>, document.getElementById('app'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

落花流雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值