首页 > 移动平台 > 详细

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

时间:2020-09-27 10:21:51      阅读:26      评论:0      收藏:0      [点我收藏+]
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)
      }
    )
  }
}

 

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

原文:https://www.cnblogs.com/zjxiang008/p/13737636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!