vue3.0 axios 请求统一处理配置,后端可以使用getParamter接收参数,也可以直接注入(仿ajax请求)

第一次搭建vue项目,对于vue默认的请求方式axios的配置还不是很熟,这里记录一下:

新建http.js

import axios from 'axios'

const TIME_OUT_MS = 60 * 1000 // 默认请求超时时间

// axios.defaults.withCredentials = true;

/*
 * @param response 返回数据列表
 */
function handleResults (response) {
  let remoteResponse = response.data

  return remoteResponse;
}

function handleUrl (url) {
  return url
}

/*
 * @param data 参数列表,这里将参数转成json字符串传输
 * @return
 */
function handleParams (data) {
  var resData = new Object();
  for (var key of Object.keys(data)) {
    resData[key] = JSON.stringify(data[key]);
  }
  return resData;
}

export default {
  /*
   * @param url
   * @param data
   * @param response 请求成功时的回调函数
   * @param exception 异常的回调函数
   */
  post (url, data, response, exception) {
    // console.info("token="+window.token);
    axios({
      method: 'post',
      url: handleUrl(url),
      data: handleParams(data),
      timeout: TIME_OUT_MS,
      transformRequest:function(data) {

        var str = [];
        for ( var p in data) {
          str.push(encodeURIComponent(p) + "="
            + encodeURIComponent(data[p]));
        }
        return str.join("&");
      },
      // 必须设置Content-Type为application/x-www-form-urlencoded,假如是application/json格式,后端接收必须加注解,而且要跨域比较麻烦,必须要明确哪些域名可以访问,不能设置所有域名访问
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'token':window.token,
      }
    }).then(
      (result) => {
        response(handleResults(result))
      }
    ).catch(
      (error) => {
        if (exception) {
          exception(error)
        } else {
          console.log(error)
        }
      }
    )
  },
  /*
   * get 请求
   * @param url
   * @param response 请求成功时的回调函数
   * @param exception 异常的回调函数
   */
  get (url, response, exception) {
    axios({
      method: 'get',
      url: handleUrl(url),
      timeout: TIME_OUT_MS,
      // headers: {'Content-Type': 'application/x-www-form-urlencoded'}
      // withCredentials: true,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        'token':window.token,
      }
    }).then(
      (result) => {
        response(handleResults(result))
      }
    ).catch(
      (error) => {
        if (exception) {
          exception(error)
        } else {
          console.log(error)
        }
      }
    )
  },
  /*
   * 导入文件
   * @param url
   * @param data
   * @param response 请求成功时的回调函数
   * @param exception 异常的回调函数
   */
  uploadFile (url, data, response, exception) {
    axios({
      method: 'post',
      url: handleUrl(url),
      data: handleParams(data),
      dataType: 'json',
      processData: false,
      contentType: false
    }).then(
      (result) => {
        response(handleResults(result, data))
      }
    ).catch(
      (error) => {
        if (exception) {
          exception(error)
        } else {
          console.log(error)
        }
      }
    )
  },
  /*
   * 下载文件用,导出 Excel 表格可以用这个方法
   * @param url
   * @param param
   * @param fileName 如果是导出 Excel 表格文件名后缀最好用.xls 而不是.xlsx,否则文件可能会因为格式错误导致无法打开
   * @param exception 异常的回调函数
   */
  downloadFile (url, data, fileName, exception) {
    axios({
      method: 'post',
      url: handleUrl(url),
      data: handleParams(data),
      responseType: 'blob'
    }).then(
      (result) => {
        const excelBlob = result.data
        if ('msSaveOrOpenBlob' in navigator) {
          // Microsoft Edge and Microsoft Internet Explorer 10-11
          window.navigator.msSaveOrOpenBlob(excelBlob, fileName)
        } else {
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          const blob = new Blob([excelBlob])
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          document.body.removeChild(elink)
        }
      }
    ).catch(
      (error) => {
        if (exception) {
          exception(error)
        } else {
          console.log(error)
        }
      }
    )
  },
  uploadFileFormData (url, data, response, exception) {
    axios({
      method: 'post',
      url: handleUrl(url),
      data: data,
      timeout: TIME_OUT_MS,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(
      (result) => {
        response(handleResults(result))
      }
    ).catch(
      (error) => {
        if (exception) {
          exception(error)
        } else {
          console.log(error)
        }
      }
    )
  }
}

在main.js中引用http.js

import http from '../src/http.js';
Vue.prototype.http = http;

使用方法

var that = this;
that.http.post(that.APIConfig.group.addStudent,data,function(res) {
        if(res.ok){
          that.applyGroup.isShowModel = true;
          that.getGroupList();
        }else{
          that.$Message.error("失败!");
        }
      },function(e) {
        that.$Message.error("程序出错,失败!");
        console.dir(e);
      })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值