vue-cli 二次封装 axios


目的是给 axios 增加拦截器!让请求头,错误处理,api等....更规范简洁的使用。

当然首先是先安装 axios

npm install axios
npm install vue-cookie --save

紧接着就是封装并配置 axios 拦截器

在src下创建utils文件夹-创建axios.js
import axios from 'axios';
import THIS from "../main";


var $axios = axios.create({
  baseURL: 'http://192.168.31.146:8010/',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});
console.log('axios', THIS)
// Add a request interceptor
$axios.interceptors.request.use(function (config) {
    console.log('request');
    console.log(config)
    if(THIS.$cookie.get('token')) {
        config.headers.token = THIS.$cookie.get('token')
    }
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });


// Add a response interceptor
$axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log('response');
    console.log(response);
    if(response.status == 200) {
        return response.data
    } else {
        alert('服务器出错')
    }
    return  ;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });


export default $axios; //暴露axios实例

在main.js里使用刚封装的axios,并且把vue实例暴漏出去

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from "./utils/axios";
import cookies from "vue-cookie";


Vue.config.productionTip = false
Vue.prototype.axios = axios;
Vue.use(cookies); // 使用cookie


var vue = new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')


export default vue

页面中直接使用

this.axios.post("login").then(res => {
  console.log(res);
});

315

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创

转载:转载请注明原文链接 - vue-cli 二次封装 axios

评论
孙瑞杰生日