在 vue-cli 3.0 + 里面对 axios 封装

在前段项目中,请求 api 以及请求方式进行封装,该封装为了简单,更加好的管理后端所给的接口,请求代码的复用性,代码简单化。

安装 axios

   $ npm install axios

创建目录文件

  1. 在src中创建 http目录
  2. 在 http 目录中创建 http.js 用户所以请求的方式
  3. 在 http 目录中创建 api.js 用于存放后端提供接口
  4. 在 http 目录中创建 axios.js 用户做 axios 拦截器
  5. 在根目录下面 创建 vue.config.js 用户 请求代理配置

接下里就是代码

项目/scr/http/http.js 中代码

import axios from 'axios';

export default {
    /**
     * get 请求
     * @param url 接口路由
     * @param auth 是否需要带登录信息
     * @returns {AxiosPromise<any>}
     */
    get(url, auth = false) {
        if (auth) {
            return axios.get(url, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.get(url);
        }
    },

    /**
     * post 请求
     *
     * @param url 接口路由
     * @param data 接口参数
     * @param auth 是否需要带登录信息
     * @returns {AxiosPromise<any>}
     */
    post(url, data, auth = false) {
        if (auth) {
            return axios.post(url, data, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.post(url, data);
        }
    },

    /**
     * put请求
     * @param url 接口路由
     * @param data 接口参数
     * @param auth 是否需要带登录信息
     * @returns {AxiosPromise<any>}
     */
    put(url, data, auth = false) {
        if (auth) {
            return axios.put(url, data, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.put(url, data);
        }
    },

    /**
     * 删除
     * @param url 接口路由
     * @param auth 是否需要带登录信息
     * @returns {AxiosPromise}
     */
    del(url, auth = false) {
        if (auth) {
            return axios.delete(url, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.delete(url);
        }
    },

    /**
     * 上传文件
     * @param url 接口路由
     * @param file 接口文件
     * @param auth 是否需要带登录信息
     */
    uploader(url, file, auth = false) {
        let param = new FormData();
        param.append('file', file)
        if (auth) {
            return axios.post(url, param, {headers: {Authorization: 'Your back-end user authenticates information'}})
        } else {
            return axios.post(url, param)
        }
    },
}

可以在 项目/scr/http/ 下面创建 一个文件 api 然后在里 根据 项目模块 创建 接口文件 方便管理

项目/scr/http/api.js 代码

import Goods from './api/goods.js';

export default {
    // 首页
    Index: {
        index: '/index/index'
    },

    // 个人中心
    Home: {
        UserInfo: '/user/info'
    },

    // 当然也可以用文件方式进行管理
    Goods: Goods

}

项目/scr/http/api/goods.js 中代码

export default {
    GoodsShow: '/goods/default'
}

项目/scr/http/axios.js 中代码

import axios from 'axios';

// 请求拦截
axios.interceptors.request.use(config => {
    // 1. 这个位置就请求前最后的配置
  // 2. 当然你也可以在这个位置 加入你的后端需要的用户授权信息
  return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(response => {
  // 请求成功
  // 1. 根据自己项目需求定制自己的拦截
  // 2. 然后返回数据
  return response;
}, error => {
    // 请求失败
      if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    // 对400错误您的处理\
                break
                case 401:
                    // 对 401 错误进行处理
                break
                default:
                // 如果以上都不是的处理
                return Promise.reject(error);
          }
    }

})

上面已经准备好了。那么接下来就是 项目/scr/min.js 中添加代码

项目/scr/min.js 中代码

import Vue from 'vue';
import App from './App.vue';
import api from './http/api';
import http from './http/http';

// axios 拦截器
import './http/axios'

// 对后端接口 进行全局注册
Vue.prototype.$api = api;
// 对请求方式 进行全局注册
Vue.prototype.$http = http;

那么接下来就是使用了

项目/src/views/index/index.vue 中我们对他进行使用

<template>
     <div>
     </div>
 </template>

<script>
  export default {
        name: "Index",
        mounted() {
            this.handle()
        },
        methods: {
            handle(){
                // 当然如果你需要带登录信息去请求这个接口 可以在 路由后面跟上 true 或者 false 来决定是否在请求的时候带登录信息
                // 我们这样进行封装 就对一个 请求封装好了。
               this.$http.get(this.$api.Index.index,true).then((result) => {
               })
            }
        }
    }
</script>

<style scoped>

</style>

接下来是 代理配置

项目/vue.config.js 代码

// 后端请求地址 注意[他会根据你环境的不同从而获取的 env 文件不同]
const target = process.env.APP_API_URL;

module.exports = {
  devServer: {
    // 所有的接口请求代理
  proxy: {
      '/api': {
        target: target,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
              '^api': ''
        }
      }
    }
  }
}

env文件区别 请参考 https://cli.vuejs.org/zh/guide/mode-and-en... 环境变量模式

以上是我个人总结,本人Vue技术有点菜。望各位大神给出不同的意见。欢迎评论

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 4年前 自动加精
自由与温暖是遥不可及的梦想
讨论数量: 3

你的思路很不错,学习了。

4年前 评论

把路径封装在 api 里

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!