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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值