第八课时: vue中axios请求拦截封装

发布时间:2019-08-12 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了第八课时: vue中axios请求拦截封装脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Ajax请求

1.解决跨域问题
出现跨域的情况(受浏览器同策略的影响):
图片描述

解决跨域的方法:

1) 前端项目增加跨域代理
        在vue.config.js文件中添加

图片描述

2) 后端增加header

第八课时: vue中axios请求拦截封装

2、封装axios
src/config/index.js:

export const baseURL = PRocess.env.NODE_ENV === 'production'
? 'http://production.COM'
: 'http://localhost:3000'

src/lib/axios.js:

import axios From 'axios'
import { baseURL } from '@/config'
class HttpRequest {
  constructor (baseUrl = baseURL) { // 如果传入参数就用传入的,没有就用baseURL
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () { // 统一添加请求参数
    const config = {
      baseURL: this.baseUrl, // axios.create 参数 baseUrl将被添加到`url`前面,除非`url`是绝对的。
      headers: {
        // 这里可以添加统一的header 如JWT登录
        // COP_Authorization: 'Bearer ' + getToken()
      }
    }
    return config
  }
  distroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) { // 请求、响应拦截
    instance.interceptors.request.use(config => { // request请求拦截
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) { // Object.keys获取队列里的属性名 如果队列里面没有请求,就添加loading...
        // Spin.show()
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    instance.interceptors.response.use(res => { // response拦截器
      // 统一增加错误提示
      this.distroy(url)
      const { data, status } = res // ES6解构赋值
      return { data, status }
    }, error => {
      this.distroy(url)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options) // 合并多个对象
    this.interceptors(instance, options.url)
    return instance(options) // 执行调用
  }
}
export default HttpRequest

src/api/index.js:

import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios

src/api/user.js:

import axios from './index'

export const getUserInfo = ({ userId }) => {
    return axios.request({
        url: '/getUserInfo',
        method: 'post',
        data: {
            userId
        }
    })
}

脚本宝典总结

以上是脚本宝典为你收集整理的第八课时: vue中axios请求拦截封装全部内容,希望文章能够帮你解决第八课时: vue中axios请求拦截封装所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。