首页 > 其他分享 >axios的第二种写法,把请求路径抽离到一个文件

axios的第二种写法,把请求路径抽离到一个文件

时间:2023-02-13 14:55:25浏览次数:51  
标签:status axios err url 写法 抽离 data response

utils/http.js

import axios from 'axios';
import qs from 'qs';
import { VALID_LOGIN } from '_config/url'
import context from '../main.js'
import router from '../router'


axios.defaults.timeout = 120000;
axios.defaults.baseURL = '';
axios.defaults.withCredentials = true;


//http request 拦截器
// axios.interceptors.request.use(
//   config => {
//     // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
//     // config.data = JSON.stringify(config.data);
//     // config.data = qs.stringify(config.data)
//     config.headers = {
//       // "Content-Type":"application/json;charset=utf-8",
//       "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
//     // }
//     // if(token){
//     //   config.params = {'token':token}
//     }
//     return config;
//   },
//   error => {
//     return Promise.reject(err);
//   }
// );

let errorFlag = true;
//http response 拦截器
axios.interceptors.response.use(
  response => {
    // if(response.data.errCode == 2){
    //   router.push({
    //     path:"/login",
    //     querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
    //   })
    // }
    return response;
  },
  error => {
    let status = error.response.status
    if (status == 403 || status == 401) {
      if (errorFlag) {
        post(VALID_LOGIN)
          .then(data => {
            if (data.status == 1 || data.status == '1') {
              context.$message({
                type: 'info',
                message: '您没有当前菜单的访问权限,请联系管理员!'
              });
            } else if (data.status == -1 || data.status == '-1') {
              context.$message({
                type: 'error',
                message: '您已掉线,请先登录!'
              });
              localStorage.clear();
              selectPlate()
              // router.push('/login')
            }
          })
          .catch(err => {
            console.log(err)
            context.$message({
              type: 'error',
              message: err.response.data.msg
            });
          })
        errorFlag = false
      }
    }
    return Promise.reject(error)
  }
)

//没有权限时返回登陆页面
$(document).ajaxComplete(function (evt, req, settings) {
  if (null != req && req != '' && req != undefined) {
    if (req.status == 403 || req.status == 401) {
      if (errorFlag = true) {
        post(VALID_LOGIN)
          .then(data => {
            if (data.status == 1 || data.status == '1') {
              context.$message({
                type: 'info',
                message: '您没有当前菜单的访问权限,请联系管理员!'
              });
            } else if (data.status == -1 || data.status == '-1') {

              context.$message({
                type: 'error',
                message: '您已掉线,请先登录!'
              });
              localStorage.clear();
              setTimeout(function () {
                selectPlate()
                // router.push('/login') 
              }, 2000);
            }
          })
          .catch(err => {
            console.log(err)
            context.$message({
              type: 'error',
              message: err.response.data.msg
            });
          })

        errorFlag = false;
      } else { }
    }
  }
});

//退出到首页
function selectPlate() {
  let a = document.createElement('a')
  a.href = location.protocol + '//' + location.host
  // a.click()
  window.location.href = location.protocol + '//' + location.host;
  const dom = window.parent.document.getElementsByClassName("menuContainer");
  const dom1 = window.parent.document.getElementsByClassName("topContainer");
  const dom2 = window.parent.document.getElementsByClassName("tabsBox");
  $(dom).css("display", "none");
  $(dom1).css("display", "none");
  $(dom2).css("display", "none");
}
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url,
      qs.stringify(data, { arrayFormat: 'repeat' }), {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
      }
    }
    )
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}
/**
* 封装getToken请求
* @param url
* @param data
* @returns {Promise}
*/
export function getToken(url, params = {}) {
  let token = document.cookie.split('=')[1]
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'TowattToken': token
      }
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}




export function postToken(url, data = {}) {
  let token = document.cookie.split('=')[1]
  return new Promise((resolve, reject) => {
    axios.post(url, JSON.stringify(data), {
      headers: {
        "Content-Type": "application/json;charset=utf-8",
        'TowattToken': token
      }
    })
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}



main.js

import { post, fetch, getToken } from './utils/http'
import { postjson, postToken, postExport } from './config/httpjson'
Vue.config.productionTip = false
Vue.prototype.$postjson = postjson;
Vue.prototype.$post = post;
Vue.prototype.$fetch = fetch;
Vue.prototype.$postToken = postToken;
Vue.prototype.$getToken = getToken;
Vue.prototype.$postExport = postExport;

组件

 this.$post(selectBuildByUser, {
        page: 1,
        size: 3000,
        provinceCode: province,
        cityCode: city,
        areaCode: area,
        buildName: value || '',
      })
        .then((res) => {
          if (res.status == 1) {
            this.optionsBuilds = res.data.rows
          }
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '网络异常,请稍后再试!',
          })
        })

标签:status,axios,err,url,写法,抽离,data,response
From: https://www.cnblogs.com/hxy--Tina/p/17116399.html

相关文章