1. 程式人生 > >封裝axios+Element-UI+攔截器

封裝axios+Element-UI+攔截器

提示:本人是新手,大家看看就好!

封裝axios,提示資訊使用的是Element-UI

1,首先安裝axios

//安裝axios
npm install axios -S

//安裝Qs
npm install qs --save-dev

//安裝Element-UI
npm i element-ui -S

//安裝less-load
npm install lessless-loader --save
或者
npm install --save-dev less-loader less

在main.js中引入

import axios from 'axios'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

{
    test: /\.less$/,
    loader: "style-loader!css-loader!less-loader"
}

//或者

{
	test: /\.less$/,
	use: [
		'style-loader',
		{ loader: 'css-loader', options: { importLoaders: 1 } },
		'less-loader'
	]
}

這裡寫圖片描述

2,封裝BaseUrl以及圖片的url

在config/dev.env.js和prod.env.js進行封裝,dev為開發環境下,prod為打包後的環境

注意:對應的值不僅需要單引號,也需要雙引號

NODE_ENV: '"production"',
BASE_URL: '"http://192.168.1.62:8952/"'

dev.env.js

這裡寫圖片描述

prod.env.js

這裡寫圖片描述

調取方法:

process.env.BASE_URL
process.env.IMAGE_URL

打包後對應的url會使用prod.env.js

import axios from 'axios'
import Qs from 'qs'

const that = this;
const params = Qs.stringify({
    currentPage: that.currentPage,
    showCount: that.showCount,
    downPaymentStatus: 1
})
axios.post(process.env.BASE_URL+'bigrichman/getBigrichmanList/', params)
      .then(function (response) {
        that.tableData = response.data.data.list
        that.totalData = response.data.data.total
      })
      .catch(function (error) {
        console.log(error)
      })

3,封裝axios

axios.js

import axios from 'axios'
import qs from 'qs'
import router from '../../router'
import {Loading, Message} from 'element-ui'
let loadinginstace; //load載入
/**
 * axios請求攔截器
 * @param {object} config axios請求配置物件
 * @return {object} 請求成功或失敗時返回的配置物件或者promise error物件
 * **/
axios.interceptors.request.use(config => {
  // 這裡的config包含每次請求的內容
  //判斷localStorage中是否存在api_token
  if (localStorage.getItem('api_token')) {
    //  存在將api_token寫入 request header
    config.headers.apiToken = `${localStorage.getItem('api_token')}`;
  }
  loadinginstace = Loading.service({fullscreen: true}) // 請求開啟loading
  return config;
}, err => {
  Message.error({
    message: '退出登陸',
    onClose: function () {
      //關閉時的回撥函式, 引數為被關閉的 message 例項
      router.push({name: 'error-404'});
    }
  })
  return Promise.reject(err);
})
/**
 * axios 響應攔截器
 * @param {object} response 從服務端響應的資料物件或者error物件
 * @return {object} 響應成功或失敗時返回的響應物件或者promise error物件
 **/
axios.interceptors.response.use(response => {
  loadinginstace.close();  // 響應成功關閉loading
  return response
}, error => {
  Message.error({
    message: '退出登陸',
    onClose: function () {
      router.push({name: 'error-404'});
    }
  })
  return Promise.resolve(error.response)
});
/**
 * 狀態碼
 */
function statusCode(response) {
  switch (response.status) {
    case 401:
      Message.error({
        message: '未授權,請登入',
        onClose: function () {
          router.push({name: 'error-404'});
        }
      })
      break
    case 403:
      Message.error({
        message: '拒絕訪問',
        onClose: function () {
          router.push({name: 'error-403'});
        }
      })
      break
    case 404:
      Message.error({
        message: '請求地址出錯',
        onClose: function () {
          router.push({name: 'error-404'});
        }
      })
      break
    case 408:
      Message.error({
        message: '請求超時',
        onClose: function () {
          router.push({name: 'error-404'});
        }
      })
      break
    case 500:
      Message.error({
        message: '伺服器內部錯誤',
        onClose: function () {
          router.push({name: 'error-500'});
        }
      })
      break
    default:
      return response
  }
}
/**
 * 請求發出後檢查返回的狀態碼,統一捕獲正確和錯誤的狀態碼,正確就直接返回response,錯誤就自定義一個返回物件
 * @param {object} response 響應物件
 * @return {object} 響應正常就返回響應資料否則返回錯誤資訊
 **/
function checkStatus(response) {
  // 如果http狀態碼正常,則直接返回資料
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    if (response.data.resultCode == '-1') {
      Message.error({
        message: '請求出錯',
        onClose: function () {
          router.push({name: 'error-404'});
        }
      })
    } else {
      return response
    }
  }else {
    // 異常狀態下,把錯誤資訊返回去
    return statusCode(response)
    // return {
    //   data:{
    //     status: 404,
    //     resultCode:'-1',
    //     resultMsg:'網路異常',
    //   }
    // }
  }
}
/**
 * 檢查完狀態碼後需要檢查後如果成功了就需要檢查後端的狀態碼處理網路正常時後臺語言返回的響應
 * @param {object} res 是後臺返回的物件或者自定義的網路異常物件,不是http 響應物件
 * @return {object} 返回後臺傳過來的資料物件,包含code,message,data等屬性,
 */
function checkCode(res) {
  // 如果code異常(這裡已經包括網路錯誤,伺服器錯誤,後端丟擲的錯誤),可以彈出一個錯誤提示,告訴使用者
  if (res.data && (res.status !== 200)) {
    return statusCode(res)
  }
  return res
}
// 請求方式的配置
export default {
  post(url, data) {  //  post
    return axios({
      method: 'post',
      baseURL: process.env.BASE_URL,
      url,
      data: qs.stringify(data),
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get(url, params) {  // get
    return axios({
      method: 'get',
      baseURL: process.env.BASE_URL,
      url,
      params, // get 請求時帶的引數
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}

路由攔截器

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import {Message} from 'element-ui'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export const page403 = {
  path: '/403',
  meta: {
    title: '403-許可權不足'
  },
  name: 'error-403',
  component: () => import('@/views/error-page/403.vue')
};
export const page404 = {
  path: '/404',
  name: 'error-404',
  meta: {
    title: '404-頁面不存在'
  },
  component: () => import('@/views/error-page/404.vue')
};
export const page500 = {
  path: '/500',
  meta: {
    title: '500-服務端錯誤'
  },
  name: 'error-500',
  component: () => import('@/views/error-page/500.vue')
};
export const pageRouter = [{
  path: '/',
  name: 'HelloWorld',
  component: HelloWorld
},{
  path: '/detail',
  name: 'detail',
  component: () => import('@/components/detail')
}]
export const router = new Router({
  routes: [page403, page404, page500, ...pageRouter]
})
export default router;

//路由守衛,路由攔截器
router.beforeEach((to, from, next) => {
  if(!to.matched || to.matched.length === 0){
    Message.error({
      message:'頁面不存在',
      duration:'2000',
      onClose:function () {
        next({
          replace: true,
          name: 'error-404'
        });
      }
    })
  }else{
    next();
  }
})

4,使用

helloWord.vue

<script>
  /* eslint-disable indent */
  import Axiox from '../views/util/axios'
  export default {
    name: 'own',
    data () {
      return {
        tableData: [],
        currentPage: 1,
        showCount: 7,
        totalData: 0,
        dialogVisible: false
      }
    },
    created () {
      this.init()
    },
    methods: {
      init () {
        const that = this
        const params = {
          currentPage: that.currentPage,
          showCount: that.showCount,
          downPaymentStatus: 1
        }
        Axiox.post('settleBigrichman/getSettleBigrichmanList/', params)
          .then(function (response) {
            that.tableData = response.data.data.list
            that.totalData = response.data.data.total
          })
          .catch(function (error) {
            console.log(error)
          })
      },
      handleSizeChange (val) {
        this.showCount = val
        this.init()
      },
      handleCurrentChange (val) {
        this.currentPage = val
        this.init()
      },
      handleClick (row, column, index) {
        console.log(row)
        console.log(column)
        console.log(index)
      },
      editClick (row, column, index) {
        this.$confirm('此操作將永久刪除該檔案, 是否繼續?', '提示', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.$message({
            type: 'success',
            message: '刪除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消刪除'
          })
        })
      }
    }
  }
</script>

這裡寫圖片描述

本文章只是自己使用,第一次寫應該有很多問題。如有錯誤請指出來,謝謝,大神勿噴