React + axios 使用

1. 简单封装使用

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

  import axios from 'axios';

  export const newVar = axios.create({
      baseURL:"http://127.0.0.1:8080",
      timeout: 5000
  })
  • 切记这里要将newVar抛出, 否则获取不到

在使用的地方直接调用

  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)
        })
  • 在这里url会自动拼接上全局url
  • 写的参数会自己带到axios对象中

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

使用.post 这类封装

封装

  export function getAPK(data){
      return newVar.post('/index', data.data, { params:{"a":"b"}, headers: {'token': 'application/x-www-form-urlencoded'}})
}
  • 这里{ 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/#拦截器

4.配置代理后不用指明, 请求的baseUrl

posted @ 2021-02-22 11:32  ShanCe-刘勇  阅读(694)  评论(0编辑  收藏  举报