zoukankan      html  css  js  c++  java
  • vue拦截器

    所谓的拦截器,其实可以理解为请求拦截,意义就是在发送请求或者响应请求之前做一些我们需要判断的事情,比如发送登录请求时判断token是否过期,是否需要携带token值,都可以在请求之前配置

    import axios from 'axios'
    
    // 配置默认的host,假如你的API host是:http://api.htmlx.club
    axios.defaults.baseURL = 'http://api.htmlx.club'
    
    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      return config
    }, function (error) {
      // 对请求错误做些什么
        return Promise.reject(error)
    });
    
    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
      // 对响应数据做点什么
      return response
    }, function (error) {
      // 对响应错误做点什么
      return Promise.reject(error)
    });
    // 请求拦截器
    request.interceptors.request.use(
      config => {
        // 开发环境下,如果请求是 post,put,patch,则打印数据体,方便调试
        if (process.env.NODE_ENV === 'development') {
          const { method } = config
          if (['post', 'put', 'patch'].includes(method)) {
            // console.log(config.data)
          }
        }
    
        return config
      },
      error => {
        notification.error({
          message: '请求失败',
          description: '发送请求失败,请检查您的网络'
        })
        return Promise.reject(error)
      }
    )
    
    // 响应拦截器
    request.interceptors.response.use(res => {
      // console.log(res)
      const jsonPattern = /application/json/gi
      if (jsonPattern.test(res.headers['content-type'])) {
        return res
      } else {
        return res
      }
    }, onError)
  • 相关阅读:
    Cookie基本使用
    Chartlet简单易用的图表控件
    JQuery 基础:6.Each的用法
    图的基本算法
    Head First Design Patterns Strategy Pattern
    个人整理的面试题
    Android从SIM卡中获取联系人
    Android 覆盖安装
    Head First Design Patterns Adapter Pattern
    android 获取sim卡运营商信息(转)
  • 原文地址:https://www.cnblogs.com/huxiuxiu/p/14887613.html
Copyright © 2011-2022 走看看