前端axios封装请求拦截器中给参数加密,响应拦截器添加解密。。js库 CryptoJS使用(详细)
// 文件
import axios from 'axios'
import crypto from "../crypto"
// 对响应参数处理,如根据状态码提示相对应错误提示,或者token失效处理重新登录处理等操作
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
const status = Number(res.status)//状态码
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
//config参数,api里面封装;
//data需要传的参数
//bool是否加密传参
export default function request(config, data = {}, bool = true) {
// access_token请求必须的
let date = new Date();
let operatorId = ""
let seq = "0001"
// let newData = ((data))//已备注封装部分
let newData = crypto.Encrypt(data)//因为前面已封装
let time = crypto.getTimeStamp(date)
let text = operatorId + newData + time + seq
let sign = crypto.HMACShaEncrypt(text) //HmacMD5( operatorId+data+timeStamp+seq)
let aesData = {
"data": newData,
"operatorId": operatorId,
"seq": seq,
"sign": sign,
"timeStamp": time //"20210122171030"
}
const Public = bool ?aesData : data;
let httpDefaultOpts = {
method: config.method || 'POST',
url: crypto.baseUrl + config.url,
headers: {
Authorization: config.needToken ? getToken('access_token') : 'Basic cGlnOnBpZw==',
'TENANT-ID': '1',
isToken: false,
},
data: Public
}
return new Promise((resolve, reject) => {
axios(httpDefaultOpts)
.then(res => {
//根据后端返回参数是否加密,对加密的进行解密
if(res.data.sign){
res = res.data.data && JSON.parse(crypto.Decrypt(res.data.data,))
if (resolveRes) {
resolve(res);
} else if (res.code === 0) {
resolve(res)
} else {
resolve(res.data)
crypto.message("err", res.data.msg)
}
}else{
console.log('不加密');
if (resolveRes) {
resolve(res);
} else if (res.data.code === 0) {
resolve(res.data)
} else {
resolve(res.data)
crypto.message("err", res.data.msg)
}
}
})
.catch(err => {
reject(err)
})
})
}