src\http\index.js:响应拦截

本文详细探讨了HTTP请求中响应拦截的实现原理和应用,包括如何在JavaScript中使用拦截器来修改、处理或拦截HTTP响应数据,以及在前端开发中这一技术的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const axios = require('axios')
import Vue from 'vue'

//const store = require('store') 可直接获取到store commonJs
import store from '../store/index' //编译顺序不能直接获取到store
import router from '../router/index'
import {
  Message,
  Loading
} from 'element-ui'
import {urlHttp} from '@/util/constant'

// 详细文档请参照 https://github.com/axios/axios

// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求花费了超过 `timeout` 的时间,请求将被中断
axios.defaults.timeout = 300000;

// `responseType` 表示服务器响应的数据类型,
//  可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
axios.defaults.responseType = 'json';
//允许请求时携带cookie
axios.defaults.withCredentials = false;
// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve;
// 否则,promise 将被 rejecte
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status < 300; // 默认的
};
//请求拦截
axios.interceptors.request.use(
  config => {
    return config
  },
  err => {
    // console.log(err)
  }
)
//响应拦截器
axios.interceptors.response.use(
  response => {
    if (isIE9()) {
      //特殊处理response
      if (response.status == 200 && response.request) {
        if (response.request.responseType === "json" && response.request.responseText) {
          response.data = JSON.parse(response.request.responseText);
        }
      }
    }
    return response
  },
  error => {
    // console.log(error.response)
    // token过期,需重新登录
    if (error.response.status == 401) {
      // token失效,记住当前页面url
      if (sessionStorage.length == 0 || sessionStorage.getItem('redirectUrl') == null || sessionStorage.getItem('redirectUrl') == '') {
        sessionStorage.setItem('redirectUrl', router.currentRoute.fullPath)
      }
      store.dispatch('ssoLogout', {'url': urlHttp}).then(function (res) {
        console.log(res, '注销返回的地址')
        store.commit('setToken', '')
        store.commit('setTokenFlag', false)
        store.commit('setLoginFlag', false)
        store.commit('setLoginUserInfo', '')
        Vue.$cookies.remove(window.iSoftCookiesKey[0], null, "h3c.com")
        Vue.$cookies.remove(window.iSoftCookiesKey[1], null, "h3c.com")
        // window.location.href = res.message
        router.push({
          path: "/testLogin"
        }).catch(err => {
        })
      }, function () {
      })
    }
    else {
      return Promise.reject(error);
    }
  }
)
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

function http(options, success, fail) {
  axios(options).then(function (response) {
    if (response == undefined) {
      // console.log('401,token过期需要重登录')
    } else if (response.data || response.data == '') {
      response.data.flag ? success(response.data) : (fail(response.data, response.data.message || "系统错误"), console.log(response.data || "系统错误"));
    } else {
      fail(null, '未收到返回数据')
    }
  })
  .catch(function (error) {
    fail({
      msg: ''
    }, '未收到返回数据')
  });
}

//导出下载的方法 为了获取response header
function httpExport(options, success, fail) {
  axios(options).then(function (response) {
    if (response == undefined) {
      // console.log('401,token过期需要重登录')
    } else if (response.data || response.data == '') {
      response.data ? success(response) : (fail(response, response.data.message || "系统错误"), console.log(response.data || "系统错误"));
    } else {
      fail(null, '未收到返回数据')
    }
  })
  .catch(function (error) {
    fail(error)
  });
}

function get(options, success, fail) {
  var requestOption = Object.assign({
    method: 'get',
    params: options.data
  }, options);
  http(requestOption, success, fail)
}

function post(options, success, fail) {
  var requestOption = Object.assign({
    method: 'post'
  }, options);
  http(requestOption, success, fail)
}

function put(options, success, fail) {
  var requestOption = Object.assign({
    method: 'put'
  }, options);
  http(requestOption, success, fail)
}

function delete1(options, success, fail) {
  var requestOption = Object.assign({
    method: 'delete'
  }, options);
  http(requestOption, success, fail)
}

function getExport(options, success, fail) {
  var requestOption = Object.assign({
    method: 'get',
    params: options.data
  }, options);
  httpExport(requestOption, success, fail)
}

function postExport(options, success, fail) {
  var requestOption = Object.assign({
    method: 'post'
  }, options);
  httpExport(requestOption, success, fail)
}

function isIE9() {
  if (
    navigator.appName == "Microsoft Internet Explorer" &&
    parseInt(
      navigator.appVersion
      .split(";")[1]
      .replace(/[ ]/g, "")
      .replace("MSIE", "")
    ) <= 9
  ) {
    return true;
  }
  return false;
}

export {
  get,
  post,
  put,
  delete1,
  getExport,
  postExport
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值