React + axios 使用

时间:2021-02-23 14:10:47   收藏:0   阅读:0

1. 简单封装使用

创建一个request组件来定义全局url

  import axios from ‘axios‘;

  export const newVar = axios.create({
      baseURL:"http://127.0.0.1:8080",
      timeout: 5000
  })

在使用的地方直接调用

  newVar({
            url:"/api/public/apk",
            method:"GET",
            // headers: {
            //     "Content-Type": "application/json"
            // },
            params:{"a":"hello"}
        }).then(res=>{
            console.log(res.data)
        }).catch(err=>{
            console.log(err)
        })

2. 将各个api请求进行封装,方便后期维护

使用.post 这类封装

封装

  export function getAPK(data){
      return newVar.post(‘/index‘, data.data, { params:{"a":"b"}, headers: {‘token‘: ‘application/x-www-form-urlencoded‘}})
}

调用

  getAPK({
            data:{"a":"index"}
        }).then(res=>{
            console.log(res)
        }).catch(err=>{
            console.log(err)
        })
使用axios对象封装
export function getAPK(data){
    console.log("data", data)
    return newVar({
        url: "/index",
        method:"POST",
        data:data.data,
        headers: {"token": "token"}
    })
}

注意: 在这里数据使用 data.data 进行传递,如果直接写data, 后台会接受到{"data": {}} 这样格式的内容, 多嵌套了一层

3.你也可以添加请求拦截器

http://www.axios-js.com/zh-cn/docs/#拦截器

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!