安装依赖
npm install axios crypto-js js-base64 --save
创建加解密文件:src/http/crypt.js
import CryptoJS from "crypto-js";
import { Base64 } from 'js-base64';
const key = CryptoJS.enc.Utf8.parse( 'KEY' )//替换成你的KEY 16位
const iv = CryptoJS.enc.Utf8.parse( 'IV' )//替换成你的IV偏移量
//加密
function enc( str ) {
if(typeof str == 'object') { str = JSON.stringify(str) }
var ciphertext = CryptoJS.AES.encrypt( str , key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return Base64.encode(ciphertext)
}
//解密
function dec( str ) {
var ciphertext = Base64.decode(str)
var decrypted = CryptoJS.AES.decrypt(ciphertext,key,{
iv: iv,
mode: CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);//WordArray对象转utf8字符串
}
export default {
enc,
dec
}
请求文件 src/http/index.js
import axios from 'axios'
import {enc,dec} from './crypt.js'
var instance = axios.create({
baseURL:'XXXXXX'
})
//请求拦截
instance.interceptors.request.use((config)=> {
console.log( config.data )
config.data =enc(config.data)
return config;
},(error)=> {
return Promise.reject(error);
});
//响应拦截
instance.interceptors.response.use((response)=> {
var res = JSON.parse(dec(response.data))
console.log(res)
return res
},(error)=> {
return Promise.reject(error);
});
export default instance
main.js
...
import http from './http/index.js'
Vue.prototype.$http = http
...
组件中使用
xxx.vue
methods:{
...
get_userinfo() {
this.$http.get('/xxx')
.....
}
...
}
网友评论