Vue axios封装 实现请求响应拦截

  1. 封装

axios.js

import axios from 'axios'
import {
  baseURL
} from '@/config'
class HttpRequest {
  constructor (baseURL = baseURL) {
    this.baseURL = baseURL
    this.queue = {} // 队列中有请求时 显示loadong界面, 反之同理
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseURL,
      header: {
        //
      }
    }
    return config
  }
  // 全局响应拦截器
  interceptors (instance, url) {
    instance.interceptors.request.use(config => { // 请求拦截器
      // 添加全局的loading...
      // Spin.show() ---遮罩组件
      // 队列中有请求时 显示loadong界面, 反之同理
      if (!Object.keys(this.queue).length) {
        // Spin.show()
      }
      this.queue[url] = true
      console.log(config)
      /*
       * {adapter: ƒ, transformRequest: {…},  * transformResponse: {…}, timeout: 0, xsrfCookieName:  * "XSRF-TOKEN", …}
       * adapter: ƒ xhrAdapter(config)
       * baseURL: undefined
       * data: undefined
       * header: {}
       * maxContentLength: -1
       * method: "get"
       * timeout: 0
       * transformRequest: {0: ƒ}
       * transformResponse: {0: ƒ}
       * url: "/userinfo"
       * validateStatus: ƒ validateStatus(status)
       * xsrfCookieName: "XSRF-TOKEN"
       * xsrfHeaderName: "X-XSRF-TOKEN"
       * __proto__: Object
       */
      return config
    }, error => {
      return Promise.reject(error)
    })

    instance.interceptors.response.use(res => { // 响应拦截器, res为服务端返回数据
      delete this.queue[url]
      console.log(res)
      /*
       * {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
       * config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
       * data: {code: 1, msg: "请先登陆"}
       * headers: {date: "Wed, 29 May 2019 17:14:59 GMT", etag: "W/"1f-DqVJ3VSipebpjnlLj9vGsYkCMOw"", x-powered-by: "Express", content-length: "31", content-type: * "application/json; charset=utf-8"}
       * request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
       * status: 200
       * statusText: "OK"
       * __proto__: Object
       */
      const {
        data,
        status
      } = res
      return {
        data,
        status
      }
    }, error => {
      delete this.queue[url]
      return Promise.reject(error)
    })
  }
  request (options) {
    console.log(options) // {url: "/userinfo", method: "get"}
    const instance = axios.create()

    // 合并为一个对象, 如果有相同的key值 后者覆盖前者
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest

api/index.js

import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios
  1. 使用

    • 创建发送请求的api
    • user.js

import axios from './index'
export const getUserInfo = ({ userId }) => {
  return axios.request({
    url: '/userinfo',
    method: 'post',
    data: {
      userId: userId
    }
  })
}
- 在页面中引入使用
- home.vue
<template>
  <div>
    <h1>home page</h1>
  </div>
</template>
<script>
import { getUserInfo } from '@/api/user';
export default {
  mounted () {
    this.getInfo()
  },
  methods: {
    getInfo () {
      getUserInfo({ userId: 21 }).then(res => {
        console.log(res)
      })
    }
  }
}
</script>
posted @ 2019-05-30 11:02  仲灏  阅读(514)  评论(0编辑  收藏  举报