• axios二次封装具有请求/响应拦截的http请求


    import axios from 'axios'
    import qs from 'qs'
    
    // 请求拦截
    axios.interceptors.request.use(config => {
      // 此处可以封装一些加载状态
      return config
    }, error => {
      return Promise.reject(error)
    })
    
    // 响应拦截
    axios.interceptors.response.use(response => {
      return response
    }, error => {
      return Promise.resolve(error.response)
    })
    
    function checkStatus (response) {
      // 此处可以封装一些加载状态
      // 如果http状态码正常,则直接返回数据
      if(response) {
        if (response.status === 200 || response.status === 304) {
          return response.data
          // 如果不需要除了data之外的数据,可以直接 return response.data
        } else if (response.status === 401) {
          location.href = '/login';
        } else {
          throw response.data
        }
      } else {
        throw {data:'网络错误'}
      }
      
    }
    
    // axios默认参数配置
    axios.defaults.baseURL = '/api/v0';
    axios.defaults.timeout = 10000;
    
    // restful API封装
    export default {
      post (url, data) {
        return axios({
          method: 'post',
          url,
          data: qs.stringify(data),
          headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        }).then(
          (res) => {
            return checkStatus(res)
          }
        )
      },
      get (url, params) {
        return axios({
          method: 'get',
          url,
          params, // get 请求时带的参数
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          }
        }).then(
          (res) => {
            return checkStatus(res)
          }
        )
      },
      del (url, params) {
        return axios({
          method: 'delete',
          url,
          params, // get 请求时带的参数
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          }
        }).then(
          (res) => {
            return checkStatus(res)
          }
        )
      }
    }
  • 相关阅读:
    搜索框
    鼠标hover时改变图片透明度和颜色(方法二)
    让背景带上颜色
    右侧固定导航栏
    react native环境配置
    左侧固定导航栏
    鼠标hover时改变图片透明度和颜色
    androidSDK配置环境变量
    cordova插件开发
    Python电子书分享
  • 原文地址:https://www.cnblogs.com/zjxiang008/p/13737636.html
Copyright © 2020-2023  润新知