因后端返回的数据量较大,后端应用 gzip 压缩数据,前端拿到接口返回的压缩数据进行解压。如图所示
咱们采纳 pako
解决压缩数据
装置
npm install pako
应用
// 导入 pako
import pako from 'pako'
// b64Data--> 传入加密的数据进行解密
function unzip (b64Data) {let strData = atob(b64Data)
// Convert binary string to character-number array
const charData = strData.split('').map(function (x) {return x.charCodeAt(0) })
// Turn number array into byte-array
const binData = new Uint8Array(charData)
// // unzip
const data = pako.inflate(binData)
// Convert gunzipped byteArray back to ascii string:
strData = String.fromCharCode.apply(null, new Uint16Array(data))
return strData
}
// 加密
function zip (str) {if (typeof str !== 'string') {str = JSON.stringify(str)
}
const binaryString = pako.gzip(str, { to: 'string'})
return btoa(binaryString)
}
export {
unzip,
zip
}
示例
引入上述 pako.js 文件
import {zip, unzip} from '@/utils/pako'
const data = {name: 'lyc', age: '18', sex: 'male'}
const compress = zip(JSON.stringify(data))
console.log(compress)
// 输入:// H4sIAAAAAAAAA6tWykvMTVWyUsqpTFbSUUpMB7ENLYDM4tQKIDM3MSdVqRYAlcYjMyYAAAA=
const unCompress = JSON.parse(unzip(compress))
console.log(unCompress)
// 输入:// {name: 'lyc', age: '18', sex: 'male'}