vue 封装axios httpRequest请求

main.js文件
vue 封装axios httpRequest请求_第1张图片
api文件
vue 封装axios httpRequest请求_第2张图片

requsest
vue 封装axios httpRequest请求_第3张图片

使用
/** 选择设备类型 */
village() {
this.request(params, this.Api.village, “get”)
.then(res => {
console.log(res)
})
.catch(error => {
this.$message.error(‘数据加载异常~’);
});
},

代码如下
main.js 入口文件

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import VueI18n from 'vue-i18n';
import { messages } from './components/common/i18n';
import 'element-ui/lib/theme-chalk/index.css'; // 默认主题
// import '../static/css/theme-green/index.css';       // 浅绿色主题
import './assets/css/icon.css';
import './components/common/directives';
import "babel-polyfill";
import request from'./components/utils/request';
import Api from './api/index';
import moment from 'vue-moment'

Vue.config.productionTip = false
Vue.use(VueI18n);
Vue.use(ElementUI, {
    size: 'small'
});
Vue.prototype.request = request;

Vue.prototype.Api = Api;//挂载原型身上

Vue.use(moment)

Vue.prototype.$Moment = moment;

const i18n = new VueI18n({
    locale: 'zh',
    messages
})

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    const role = JSON.parse(sessionStorage.getItem('userItem'));
    if (!role && to.path !== '/login') {
        next('/login');
    } else if (to.meta.permission) {
        // 如果是管理员权限则可进入,这里只是简单的模拟管理员权限而已
        role === 'admin' ? next() : next('/403');
    } else {
        // 简单的判断IE10及以下不进入富文本编辑器,该组件不兼容
        if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
            Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器,请使用更高版本的浏览器查看', '浏览器不兼容通知', {
                confirmButtonText: '确定'
            });
        } else {
            next();
        }
    }
})


new Vue({
    router,
    i18n,
    render: h => h(App)
}).$mount('#app')

request封装

import Axios from 'axios'
import queryString from 'querystring'
import { Message } from 'element-ui';
// Vue.use(Message)

const baseUrl = 'http://usl'//接口地址

/**
 * @desc 清除请求参数中字符串的空白
 * @param data {object}
 * @returns {*}
 */
function removeParamsSpace(data) {
  if (!data) return null

  if (Object.prototype.toString.call(data) !== '[object Object]') {
    return data
  }
  const newData = {}
  // 字符串移除空白的白名单
  const whiteList = ['introduce']
  for (const key in data) {
    if (!whiteList.includes(key) && data[key] instanceof String) {
      newData[key] = data[key].trim()
    } else {
      newData[key] = data[key]
    }
  }
  return newData
}

  /** 去除空隙 */
  function  removeEmpty(obj) {
      Object.keys(obj).forEach(function(key) {
        (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) || (obj[key] === undefined || obj[key] === null || obj[key] === "") && delete obj[key]
      });
      return obj;
  }

/**
 * @desc 最终的网络请求函数,根据不同的请求方法做不同的事情
 * @param params
 * @param method
 * @param path
 * @param baseURL
 * @returns {Promise<*>}
 */
async function fetch(params, method, path, baseURL) {

  /**
  * @desc Axios 实例
  * @type {AxiosInstance}
  */
  const axios = Axios.create({
    baseURL: baseUrl,
    headers: {
      'Authorization': path === '/user/loginUser' ? '' : sessionStorage.getItem('token'),
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',

    },
    withCredentials: true
  })

  switch (method.toLocaleLowerCase()) {
    case 'get':
      return axios.get(path, {
        baseURL,
        params: removeEmpty(params)
      })


    case 'delete':
      return axios.delete(path, {
        baseURL,
        data: queryString.stringify(params)
      })

    case 'post':
      return axios.post(path, queryString.stringify(params), { baseURL })

    case 'put':
      return axios.put(path, queryString.stringify(params), { baseURL })

    case 'patch':
      return axios.patch(path, queryString.stringify(params), { baseURL })

    // 有 jsonp 需求再加
    // eslint-disable-next-line
    // case 'jsonp':
    default:
      return axios({ path, baseURL, method, params })
  }
}

/**
 * @desc 对请求结果进行处理
 * @param result {any} - 请求结果
 * @param success {boolean?} - 是否成功
 * @returns {object}
 */
function formatResult(result, success) {
  // 成功结果
  if (success) {
    const { statusText, status, data } = result
    if ([401].includes(data.errorCode)) {
      window.location.href = `${window.location.origin}/#/login`;
    }

    return {
      success: true,
      message: statusText,
      statusCode: status,
      ...data
    }
  }
  function tips() {
    Message({
      showClose: true,
      message: '您的会话已过期,或者账号在别处登录!请重新登录',
      type: 'warning'
    })
  }

  // 失败结果
  const { response } = result
  if (response.data.errorCode === 401) {
    setTimeout(() => {
      window.location.href = `${window.location.origin}/#/login`;
    }, 3000);
    tips()
  }
  let msg
  let statusCode
  if (response && response instanceof Object) {
    const { data, statusText } = response
    statusCode = response.status
    msg = data.message || statusText
  } else {
    statusCode = 600
    msg = result.message || 'Network Error'
  }
  return { success: false, statusCode, message: msg }
}

/**
 * @desc 网络请求函数
 * @param path {string} - 接口路径, 如果路径以mock开头,会调用本地mock接口的数据(只有开发环境会使用,生产环境不会使用)
 * @param [method] {string} - 合法值= get, post, jsonp, delete, put, patch
 * @param [baseURL] {string} - 如果请求地址是其他项目或外部的地址
 * @param [params] {object} - 请求参数
 * @returns {Promise}
 */
export default async function request(params, path, method = 'get', baseURL = baseUrl) {
  if (!path) {
    throw new Error('方法必须传入接口路径参数')
  }
  const cloneData = removeParamsSpace(params)

  try {
    const result = await fetch(cloneData, method, path, baseURL)
    return formatResult(result, true)
  } catch (error) {
    return formatResult(error, false)
  }
}


使用


init() {
 this.request(params, this.Api.login, "get")
}

api

export default {
    login: '/user/loginUser',//登陆
}

你可能感兴趣的:(vue封装http请求,vue.js,javascript,es6)