React axios 安装与使用

167 阅读1分钟

axios 基于Promise的HTTP客户端,用于浏览器和node.js github:github.com/axios/axios

安装axios
npm install axios
使用axios
import React, {Component, Fragment} from 'react'
import Http from "axios"; //导入axios

class Index extends Component {
    render(){
      return <div>Hello</div>
    }
    componentDidMount() {
        /* Http = axios
         * Http调用里面的get方法
         * data是参数 get需要key params post不需要直接{id: '007'}
         * .then()成功回调
         * .catch()失败回调
         */
        let data = {
          params:{
              id: '007'
          }
        }
        Http.get('/api/todolist', data).then(res => {
            console.log(res)
        }).catch(error => {
            console.error(error)
        })
    }
}

exprot default Index
axios最好进行函数封装,做拦截器等需要统一的功能;后面如有时间进行更新。