vue Interface Request Encryption Instance

  • 2021-08-06 20:23:43
  • OfStack

1. Install the vue project npm init webpack project

2 Install iview npm i iview-save (this is used in combination with iview framework, which can be installed according to your own needs, of course, you can not install it)

3 in the src directory to build 1 utils folder inside need to put 5 js are encapsulated good js file function is not limited to encryption can be studied 1 you will learn a lot of things

1.api.js


/**
 *  For vue Instance addition http Method 
 * Vue.use(http)
 */
import http from './http'
 
export default {
 /**
 * install Hook 
 * @param {Vue} Vue Vue
 */
 install (Vue) {
 Vue.prototype.http = http
 }
}

2. filters.js


//  Public use filters
import Vue from 'vue';
import {getTime, getPrdType} from '../utils/time';
 
 
//  Differentiating payment methods filter
Vue.filter('paywayType', function (value) {
 return value;
});
 
//  Time 
Vue.filter('newdate', function (value) {
 return getTime(value);
});
//  Time - Minutes 
Vue.filter('minute', function (str, n) {
 const num = parseInt(n);
 return str.split(' ')[num];
});
//  Partition to: concatenate multiple parameters string
Vue.filter('valStr', function (str, n) {
 const num = parseInt(n);
 return str.split(':')[num];
});
//  Calculate the countdown according to the provided time 
Vue.filter('countDown', function (str) {
 const dateStr = new Date(str).getTime();
 const timeNow = new Date().getTime();
 const countDown = dateStr - timeNow;
 const countDownDay = Math.floor((dateStr - timeNow) / 86400000);//  Calculate the remaining days 
 const countDownHour = Math.floor((dateStr - timeNow) / 3600000 % 24);//  Calculate remaining hours 
 const countDownMin = Math.floor((dateStr - timeNow) / 60000 % 60);//  Calculate the remaining minutes 
 // const countDownSec = Math.floor((dateStr - timeNow) / 1000 % 60);//  Calculate the remaining seconds 
 if (countDown <= 0) {
  return '- - - -';
 } else {
  return countDownDay + ' Days ' + countDownHour + ' Hours ' + countDownMin + ' Minutes ';
 }
});
//  Take an absolute value 
Vue.filter('numberFn', function (numberStr) {
 return Math.abs(numberStr);
});
//  Object that handles the address of the picture filter
Vue.filter('imgSrc', function (src) {
 const env = getPrdType();
 switch (env) {
  case 'pre':
   return `https://preres.bldz.com/${src}`;
  case 'pro':
   return `https://res.bldz.com/${src}`;
  case 'test':
  default:
   return `https://testimg.bldz.com/${src}`;
 }
});
//  Residual time of direct conversion 
Vue.filter('dateShow', function (dateStr) {
 const countDownDay = Math.floor(dateStr / 86400);//  Calculate the remaining days 
 const countDownHour = Math.floor(dateStr / 3600 % 24);//  Calculate remaining hours 
 const countDownMin = Math.floor(dateStr / 60 % 60);//  Calculate the remaining minutes 
 // const countDownSec = Math.floor((dateStr - timeNow) / 1000 % 60);//  Calculate the remaining seconds 
 if (dateStr <= 0) {
  return '- - - -';
 } else if (countDownDay <= 0 && countDownHour <= 0) {
  return countDownMin + ' Minutes ';
 } else if (countDownDay <= 0) {
  return countDownHour + ' Hours ' + countDownMin + ' Minutes ';
 } else {
  return countDownDay + ' Days ' + countDownHour + ' Hours ' + countDownMin + ' Minutes ';
 }
});
//  Processing pictures 
Vue.filter('imgLazy', function (src) {
 return {
  src,
  error: '../static/images/load-failure.png',
  loading: '../static/images/default-picture.png'
 };
});
Vue.filter('imgHandler', function (src) {
 return src.replace(/,jpg/g, '.jpg');
});

3.http.js


import axios from 'axios'
import utils from '../utils/utils'
import {Modal} from 'iview'
// import qs from 'qs';
axios.defaults.timeout = 1000*60
axios.defaults.baseURL = ''
const defaultHeaders = {
 Accept: 'application/json, text/plain, */*; charset=utf-8',
 'Content-Type': 'application/json; charset=utf-8',
 Pragma: 'no-cache',
 'Cache-Control': 'no-cache'
}
//  Set the default header 
Object.assign(axios.defaults.headers.common, defaultHeaders)
 
const methods = ['get', 'post', 'put', 'delete']
 
const http = {}
methods.forEach(method => {
 http[method] = axios[method].bind(axios)
})
export default http
export const addRequestInterceptor =
 axios.interceptors.request.use.bind(axios.interceptors.request)
// request Auto-add before api Configure 
addRequestInterceptor(
 (config) => {
 if (utils.getlocal('token')) {
  //  Judge whether it exists or not token , if any, then each http header Add them all token
  config.headers.Authentication = utils.getlocal('token')
 }
 // config.url = `/api${config.url}`
 return config
 },
 (error) => {
 return Promise.reject(error)
 }
)
 
export const addResponseInterceptor =
axios.interceptors.response.use.bind(axios.interceptors.response)
addResponseInterceptor(
 (response) => {
 //  Be unified here 1 Pre-processing request response 
 if (Number(response.status) === 200) {
  //  Global notify If there is a problem, I'd better deal with it myself 
  // return Promise.reject(response.data)
  // window.location.href = './'
  // this.$router.push({ path: './' })
 }
 return Promise.resolve(response.data)
 },
 (error) => {
 if (error.response) {
  const title = ' Warm Tips ';
  const content = '<p> Please log in again after login expires </p>'  
  switch (error.response.status) {
  case 401:
   //  Return  401  Jump to login page   
   Modal.error({
   title: title,
   content: content,
   onOk: () => {
    localStorage.removeItem("lefthidden")
    localStorage.removeItem("leftlist")
    localStorage.removeItem("token")
    localStorage.removeItem("userInfo")
    localStorage.removeItem("headace")
    localStorage.removeItem("sideleft")
    utils.delCookie("user");
    window.location.href = './'
   }
  })
   break
  }
 }
 return Promise.reject(error || ' There's been a mistake ')
 }
)

4. time.js


//  Common tools api
 
const test = 'test';
const pre = 'pre';
const pro = 'pro';
 
export function judeType (param, typeString) {
 if (Object.prototype.toString.call(param) === typeString) return true;
 return false;
};
 
export function isPrd () {
 return process.env.NODE_ENV === 'production';
};
 
export function getPrdType () {
 return ENV;
};
 
export const ls = {
 put (key, value) {
  if (!key || !value) return;
  window.localStorage[key] = JSON.stringify(value);
 },
 get (key) {
  if (!key) return null;
  const tem = window.localStorage[key];
  if (!tem) return null;
  return JSON.parse(tem);
 },
 //  Settings cookie
 setCookie (key, value, time) {
  if (time) {
   let date = new Date();
   date.setDate(date.getDate() + time);
   document.cookie = key + '=' + value + ';expires=' + date.toGMTString() + ';path=/';
  } else {
   document.cookie = key + '=' + value + ';path=/';
  }
 },
 //  Get cookie
 getCookie (key) {
  let array = document.cookie.split('; ');
  array.map(val => {
   let [valKey, value] = val.split('=');
   if (valKey === key) {
    return decodeURI(value);
   }
  });
  return '';
 }
};
 
/**
 *  Determines whether the element has the class
 * @param {*} el
 * @param {*} className
 */
 
export function hasClass (el, className) {
 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
 return reg.test(el.className);
}
/**
 *  Add for the element class
 * @param {*} el
 * @param {*} className
 */
export function addClass (el, className) {
 if (hasClass(el, className)) return;
 let newClass = el.className.spilt(' ');
 newClass.push(className);
 el.className = newClass.join(' ');
}
 
export function removeClass (el, className) {
 if (!hasClass(el, className)) return;
 
 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
 el.className = el.className.replace(reg, ' ');
}
 
/**
 *  Store data in tags 
 * @param {*} el
 * @param {*} name
 * @param {*} val
 */
export function getData (el, name, val) {
 let prefix = 'data-';
 if (val) {
  return el.setAttribute(prefix + name, val);
 }
 return el.getAttribute(prefix + name);
}
 
export function isIphone () {
 return window.navigator.appVersion.match(/iphone/gi);
}
 
/**
 *  Calculate the positional relationship between elements and windows 
 * @param {*} el
 */
export function getRect (el) {
 if (el instanceof window.SVGElement) {
  let rect = el.getBoundingClientRect();
  return {
   top: rect.top,
   left: rect.left,
   width: rect.width,
   height: rect.height
  };
 } else {
  return {
   top: el.offsetTop,
   left: el.offsetLeft,
   width: el.offsetWidth,
   height: el.offsetHeight
  };
 }
}
 
/**
 *  Method for obtaining uncertain data api
 * @param {Array} p  Array of parameters 
 * @param {Object} o  Object 
 */
export function getIn (p, o) {
 return p.reduce(function (xs, x) {
  return (xs && xs[x]) ? xs[x] : null;
 }, o);
}
 
/**
 *  Time stamp changed to year, month and day format time 
 * @param {*} p  Time stamp 
 */
export function getTime (p) {
 let myDate = new Date(p);
 let year = myDate.getFullYear();
 let month = myDate.getMonth() + 1;
 let date = myDate.getDate();
 if (month >= 10) {
  month = '' + month;
 } else {
  month = '0' + month;
 }
 
 if (date >= 10) {
  date = '' + date;
 } else {
  date = '0' + date;
 }
 return year + '-' + month + '-' + date;
}
 
export function debounce (method, delay) {
 let timer = null;
 return function () {
  let context = this;
  let args = arguments;
  clearTimeout(timer);
  timer = setTimeout(function () {
   method.apply(context, args);
  }, delay);
 };
}
 

5 utils.js


//  Get cookie , 
export function getCookie (name) {
 if (document.cookie.length > 0){
 let c_start = document.cookie.indexOf(name + '=')
 if (c_start != -1) { 
  c_start = c_start + name.length + 1 
  let c_end = document.cookie.indexOf(';', c_start)
  if (c_end == -1) c_end = document.cookie.length
  return unescape(document.cookie.substring(c_start, c_end))
 }
 }
 return ''
}
//  Settings cookie, Increase to vue Instance for global invocation 
export function setCookie (cname, value, expiredays) {
 let exdate = new Date()
 exdate.setDate(exdate.getDate() + expiredays)
 document.cookie = cname + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
}
//  Delete cookie
export function delCookie (name) {
 let exp = new Date()
 exp.setTime(exp.getTime() - 1)
 let cval = getCookie(name)
 if (cval != null) {
 document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
 }
}
//  Settings localstorage
export function putlocal (key, value) {
 if (!key || !value) return
 window.localStorage[key] = JSON.stringify(value)
}
//  Get localstorage
export function getlocal (key) {
 if (!key) return null
 const tem = window.localStorage[key]
 if (!tem) return null
 return JSON.parse(tem)
}
/**
 * use_iframe_download function -  Pass  iframe  Download a file 
 *
 * @param {String} download_path  Links to files to download 
 * @return {Void}
 */
export const use_iframe_download = download_path => {
 const $iframe = document.createElement('iframe')
 
 $iframe.style.height = '0px'
 $iframe.style.width = '0px'
 document.body.appendChild($iframe)
 $iframe.setAttribute('src', download_path)
 
 setTimeout(function () { $iframe.remove() }, 20000)
}
 
function requestTimeout (xhr) {
 const timer = setTimeout(() => {
 timer && clearTimeout(timer)
 xhr.abort()
 }, 5000)
 return timer
}
//  Export 
export function exporttable (httpUrl,token, formData, callback) {
let i = formData.entries();
 let param = "?Authentication="+token;
 do{
 var v = i.next();
 if(!v.done){
  param+="&"+v.value[0]+"="+v.value[1];  
 }
 
 }while(!v.done);
// console.log(param);
window.open(httpUrl+param)
// var xhr = new XMLHttpRequest()
// if (xhr.withCredentials === undefined){ 
// return false
// };
// xhr.open("post", httpUrl)
// // xhr.timeout=5000
// xhr.setRequestHeader("Authentication", token)
// xhr.responseType = "blob"
// let timer = requestTimeout(xhr)
// xhr.onreadystatechange = function () {
// timer && clearTimeout(timer)
// if (xhr.readyState !== 4) {
// timer = requestTimeout(xhr)
// return
// }
// if (this.status === 200) {
// var blob = this.response
// var contentType = this.getResponseHeader('content-type')
// var fileName = contentType.split(";")[1].split("=")[1]
// fileName = decodeURI(fileName)
// let aTag = document.createElement('a')
// //  Downloaded file name 
// aTag.download = fileName
// aTag.href = URL.createObjectURL(blob)
// aTag.click()
// URL.revokeObjectURL(blob)
callback && callback(true)
// } else {
// callback && callback(false)
// } 
// }
// xhr.send(formData);
}
 
//  Get the current time 
export function getNowFormatDate() {
 var date = new Date();
 var seperator1 = "-";
 var seperator2 = ":";
 var month = date.getMonth() + 1;
 var strDate = date.getDate();
 if (month >= 1 && month <= 9) {
  month = "0" + month;
 }
 if (strDate >= 0 && strDate <= 9) {
  strDate = "0" + strDate;
 }
 var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
   + " " + date.getHours() + seperator2 + date.getMinutes()
   + seperator2 + date.getSeconds();
   
 return currentdate;
}
 
//  Time formatting 
export function formatDate(date, fmt) {
 if (/(y+)/.test(fmt)) {
  fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
 }
 let o = {
  'M+': date.getMonth() + 1,
  'd+': date.getDate(),
  'h+': date.getHours(),
  'm+': date.getMinutes(),
  's+': date.getSeconds()
 };
 for (let k in o) {
  if (new RegExp(`(${k})`).test(fmt)) {
   let str = o[k] + '';
   fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
  }
 }
 return fmt;
};
 
function padLeftZero(str) {
 return ('00' + str).substr(str.length);
}
export default {
 getCookie,
 setCookie,
 delCookie,
 putlocal,
 getlocal,
 exporttable,
 getNowFormatDate,
 formatDate
}

4. Configure main. js


import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from 'vue-router';
import iView from 'iview';
import 'iview/dist/styles/iview.css'
import http from './utils/http'
import Api from './utils/api'
import utils from './utils/utils'
import './utils/filters'
 
Vue.config.productionTip = false
Vue.use(VueRouter);
Vue.use(iView);
 
Vue.use(http)
Vue.use(Api)
Vue.use(utils)
/* eslint-disable no-new */
 
global.BASE_URL = process.env.API_HOST
 
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>'
})

5. Locate dev. env. js under the config folder


module.exports = merge(prodEnv, {
 NODE_ENV: '"development"',
 API_HOST: '" Development environment interface address "'
})

6. How to use it in the page


<template>
 <div class="hello">
  <Select v-model="model8" clearable style="width:200px">
  <Option v-for="item in cityList" :value="item.productCode" :key="item.productCode">{{item.productName }}</Option>
 </Select>
 </div>
</template>
 
<script>
export default {
 name: 'HelloWorld',
 data () {
 return {
  cityList:[],
  model8:"code"
 }
 },
 mounted(){
 this.http
  .post(BASE_URL + " Request path ",{})
  .then(data => {
  if (data.code == "success") {
 this.cityList = data.data;
 this.cityList.splice(0,0,{ productCode: "code", productName: " All products " })
  }
  })
  .catch(err => {
  console.log(err);
  });
 }
}
</script>
<style scoped>
</style>

Related articles: