vue接口请求封装request.js以及common.js实现接口请求

话不多说,直接上代码:
request.js和common.js放在同一个文件夹下 方便使用,其中common.js是一个工具类js,里面还写了 其他方法 ,可按需自取
1、request.js

import Axios from 'axios'
import router from '../router/index'
import qs from 'qs.js'
import {
  Loading,
  Message
} from 'element-ui'
//创建一个axios对象
const instance = Axios.create({
  baseURL:'/api',//会在发送请求时候拼接在url参数前面
  timeout:5000,//请求5s超时
  withCredentials: true // 是否允许带cookie这些
})

//全局请求拦截
//表示所有的网络请求都会先走这个方法
//我们可以在它里面添加一些自定义的内容
instance.interceptors.request.use(
  function (config) {
    console.group('全局请求拦截')
    console.log(config)
    console.groupEnd()
    config.headers.token = '12345'//例如可以在请求头里面设置token值,token变量名前后端约定
    return config;
  },
  function (err) {
    return Promise.reject(err);
  },

)

//全局响应拦截
//表示所有网络请求返回数据之后都会先执行此方法
//此处可以根据服务器返回的状态码做相应的处理
//如根据请求状态码404/401/500等做相应的处理,页面跳转等
// response过滤器
Axios.interceptors.response.use(
  // 正确处理
  res => {
    let data = res.data;
    return data;
  },
  // 错误处理
  error => {
    let res = error.response;
    if (res) {
      switch (res.status) {
        //401 登录过期 返回登录
        case 401:
          Message.error({
            message: '登录过期,请重新登录'
          });
          router.replace({
            path: '/login?flag=true'
          })
          break;
      }
    } else {
      // console.log;
      Message.error({
        message: '网络错误,请刷新重试'
      });
    }
    return Promise.reject(error);
  }
);

// url传参
function urlParams (method, url, params) {
  return new Promise((resolve, reject) => {
    Axios({
      url,
      method,
      params,
      headers: {
        "Content-Type": "application/json;charset=UTF-8"
      }
    }).then(
      res => {
        resolve(res);
      },
      error => {
        reject(error)
      }
    )
      .catch((error) => {
        reject(error);
      })
  })
}

// body传参
function bodyParams (method, url, params, contentType) {
  return new Promise((resolve, reject) => {
    Axios({
      url,
      method,
      data: contentType == 'json' ? params : qs.stringify(params),
      headers: {
        "Content-Type": contentType == 'json' ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(
      res => {
        resolve(res);
      },
      error => {
        reject(error)
      }
    ).catch((error) => {
      reject(error);
    })
  })
}

// body传参上传文件
function bodyParams1 (method, url, params) {
  return new Promise((resolve, reject) => {
    Axios({
      url,
      method,
      data: params,
      headers: {
        "Content-Type": 'multipart/form-data'
      }
    }).then(
      res => {
        resolve(res);
      },
      error => {
        reject(error)
      }
    ).catch((error) => {
      reject(error);
    })
  })
}

export function fetchGet (url, params = '') {
  return urlParams("get", url, params);
}

export function fetchDelete (url, params = '') {
  return urlParams("delete", url, params);
}

export function fetchPost (url, params, contentType) {
  return bodyParams("post", url, params, contentType);
}

export function fetchPut (url, params, contentType) {
  return bodyParams("put", url, params, contentType);
}

export function fetchPostFile (url, params, contentType) {
  return bodyParams1("post", url, params, contentType);
}

2、common.js

import * as http from './request'
export default {
  install (Vue, options) {
    /**
     * 请求方法
     * */
    Vue.prototype.$fetchGet = http.fetchGet;
    Vue.prototype.$fetchPost = http.fetchPost;
    Vue.prototype.$fetchPut = http.fetchPut;
    Vue.prototype.$fetchDelete = http.fetchDelete;
    Vue.prototype.$fetchPostFile = http.fetchPostFile;

    /**
     *@method 返回功能
     */
    Vue.prototype.getBack = function () {
      this.$router.go(-1)
    }

    /**
     *@method 判断子串
     *@param {String} 需要判断的子串
     *@return {Boolean}
     */
    Vue.prototype.isContains = function (substr) {
      var str = localStorage.getItem("auth");
      return new RegExp(substr, 'g').test(str);
    };

    /**
     *@method 删除文件的时间戳
     *@param {Str} 文件名
     *@return {Str} 删除时间戳后的文件名
     * */
    Vue.prototype.deletetimestamp = function (name) {
      let str = '';
      let oldname = name.lastIndexOf('.');
      let fileName = name.substring(0, oldname);
      let fileType = name.substring(oldname, oldname.length)
      fileName = fileName.substring(0, fileName.length - 13);
      str = fileName + fileType;
      return str;
    };

    /**
     * @method 获取cookie
     * @param {String} 获取coolie的key
     * @return {String} 获取coolie的value
     */
    Vue.prototype.getCookie = function (name) {
      var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
      } else {
        return null;
      }
    };

    /**
     * @method 深拷贝
     * @param {Obj} 需要拷贝的 对象 数组
     * @return {Obj}
     */
    Vue.prototype.cloneObj = function (obj) {
      let _this = this;
      let str, newobj = obj.constructor === Array ? [] : {};
      if (typeof obj !== 'object') {
        return;
      } else if (window.JSON) {
        str = JSON.stringify(obj);
        newobj = JSON.parse(str);
      } else {
        for (var i in obj) {
          newobj[i] = typeof obj[i] === 'object' ? _this.cloneObj(obj[i]) : obj[i];
        }
      }
      return newobj;
    };

    /**
     * 全局过滤 时间
     * */
    Vue.filter('FormatTime', (value, arg) => {
      if (value) {
        return new Date(value).Format(arg)
      }
    });

    /**
     * 全局过滤 性别
     * */
    Vue.filter('FormatSex', (value) => {
      if (value == 0) {
        return "男"
      } else if (value == 1) {
        return "女"
      }
    });
    /**
     * 时间格式处理方法
     * @return {string}
     */
    Vue.prototype.FormatDate = function(date) {
      let nstr = new Date(date) //当天时间
      let now_year = nstr.getFullYear() //年份
      let now_month =
          nstr.getMonth() + 1 < 10
              ? '0' + (nstr.getMonth() + 1)
              : nstr.getMonth() + 1 //月份
      let now_day = nstr.getDate() < 10 ? '0' + nstr.getDate() : nstr.getDate() //日期
      let now_hours =
          nstr.getHours() < 10 ? '0' + nstr.getHours() : nstr.getHours() //时
      let now_minut =
          nstr.getMinutes() < 10 ? '0' + nstr.getMinutes() : nstr.getMinutes() //分
      let now_second =
          nstr.getSeconds() < 10 ? '0' + nstr.getSeconds() : nstr.getSeconds() //秒
      return (
          now_year +
          '-' +
          now_month +
          '-' +
          now_day +
          ' ' +
          now_hours +
          ':' +
          now_minut +
          ':' +
          now_second
      )
    }
  }

}


并且在mian.js中对进行引入

import common from './api/common'
Vue.use(common)

3、跨域配置
config文件下index.js下module.exports中添加proxyTable配置

proxyTable: {//用代理的方式实现跨域访问
      '/': {
        target: 'http://152.136.185.210:7878/api/m5',    //设置你调用的接口域名和端口号
        changeOrigin: true,    //true表示允许跨域,有人说false也可以,我没试过
        pathRewrite: {
          '/api': ''   //请求接口时直接用/api = http://123.456.789.123:8081/abc
        }
      }
    },

4、组件内接口请求测试

<template>
  <div>
    <!--接口请求封装测试-->
    <button @click="getAxiosMethods">未封装接口请求get</button>
    <button @click="getMyAxiosMethods">封装接口请求get</button>
    <div>

    </div>
  </div>
</template>
<script>
  import axios from 'axios'
  /*import '../../api/request'
  import {fetchGet} from '../../api/request'*/
  export default {
    data(){
      return{

      }
    },
    methods:{
      //接口请求测试
      //未封装
      getAxiosMethods(){
        axios.get('http://152.136.185.210:7878/api/m5/home/multidata',{
          params:{
          },headers:{}
        }).then(res=>{
          console.log(res,'未封装')
        })
      },
      //已封装
      getMyAxiosMethods(){
        //未设置baseUrl时候
        /*get('http://152.136.185.210:7878/api/m5/home/multidata',{}).then(res=>{
          console.log(res,'已封装')
        })*/
        //设置baseUrl时候
        this.$fetchGet('/home/multidata',{}).then(res=>{
          console.log(res,'已封装')
        })
      },
    }
  }
</script>
<style lang="scss" scoped>

</style>

请求成功
在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值