在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 —— 用户请求代理配置

三、代码

1、http.js 中代码

//   http.js   用户所有请求的方式
import axios from 'axios';

export default {
    /**
     * get 请求
     * @param url 接口路由
     * @param auth 是否需要带登录信息
     * @returns {AxiosPromise}
     * (Your back-end user authenticates information )
     * 			↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
     * 	后端用户验证信息比如(token)		
     */
    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}
     * 
     */
    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}
     */
    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)
        }
    },
}

2、api.js 代码

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

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

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

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

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

goods.js 代码

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

3、axios.js 代码

//	axios.js
import axios from 'axios';

// 请求拦截
axios.interceptors.request.use(config => {
    // 1. 这个位置是请求前最后的配置
  	// 2. 当然你也可以在这个位置 加入你的后端需要的用户授权信息
 	 // 	config.headers.authorization = `Bearer ${localStorage.getItem('token')}`
  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);
          }
    }
})

4、做好前面的准备后,在项目 /scr/min.js 中添加代码

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

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: {
  /*
  * @param target  要访问的接口域名
  * @param changeOrigin 
  * 	开启代理:在本地会创建一个虚拟服务端,
  * 	然后发送请求的数据,并同时接收请求的数据,
  * 	这样服务端和服务端进行数据的交互就不会有跨域问题
  * @param ws	是否启用 websockets
  * @param pathRewrite 
  * 	这里理解成用'/api'代替 target 里面的地址,
  * 	比如要调用'http://40.00.100.100:3002/user/add',
  * 	直接写'/api/user/add'即可
  * 
  */
      '/api': {
        target: target, 
        changeOrigin: true, 
        ws: true, 
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

env 文件区别 请参考 环境变量和模式

你可能感兴趣的:(Vue)