业务场景:假设要将一下类似登录信息或者用户信息直接存储在localstorage或者sessionStorage,那么会存在安全隐患,本文介绍其中一种优化方法,就是通过base64编码解码
base64思想如下:
// 将对象序列化为JSON字符串
let jsonString = JSON.stringify(sessionStore);
// 对JSON字符串进行Base64编码
let base64String = window.btoa(jsonString); // 注意:btoa是浏览器提供的方法,用于将ASCII字符串编码为Base64格式
// // // 后续若要恢复对象
let decodedJsonString = window.atob(base64String); // 解码Base64字符串
let restoredObject = JSON.parse(decodedJsonString); // 反序列化为原对象
实际应用结合sessionStorage:
// 假设有一个复杂对象
let sessionStore = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St.",
city: "New York"
}
};
// 将对象序列化为JSON字符串
let jsonString = JSON.stringify(sessionStore);
// 对JSON字符串进行Base64编码
let base64String = window.btoa(jsonString); // 注意:btoa是浏览器提供的方法,用于将ASCII字符串编码为Base64格式
sessionStorage.setItem('jimoTrackerSessionStore', base64String); // 数据进行编码成字符串后存储起来。
在其他页面存取使用:假设在其他ts文件里:
//获取存储的base64编码
let jimoTrackerSession= sessionStorage.getItem('jimoTrackerSessionStore') as string;
// base64解码要恢复对象
let decodedJsonString = window.atob(jimoTrackerSession); // 解码Base64字符串
ctx.sessionStore = JSON.parse(decodedJsonString); // 反序列化为原对象
console.log(ctx.sessionStore.age) //30,取值成功
以上所有逻辑精简一下:
let sessionStore = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St.",
city: "New York"
}
};
sessionStorage.setItem('jimoTrackerSessionStore', window.btoa(JSON.stringify(sessionStore))); // 数据持久化
ctx.sessionStore = JSON.parse(window.atob(sessionStorage.getItem('jimoTrackerSessionStore') as string)|| '{}');
console.log(ctx.sessionStore.age) //30,取值成功