[英]JS - atob() The string to be decoded contains invalid characters
I'm having some string conversion issues in JS. 我在JS中遇到了一些字符串转换问题。 I have a json object that I want to base64 encode and store as a client side cookie. 我有一个json对象,我想base64编码并存储为客户端cookie。 It seems simple enough but for some reason the JS atob
is just not working for me. 这似乎很简单,但出于某种原因,JS atob
不适合我。 I keep getting this error 我一直收到这个错误
InvalidCharacterError: The string to be decoded contains invalid characters. InvalidCharacterError:要解码的字符串包含无效字符。
Here is a simplified version of why I'm trying to accomplish: 这是我想要完成的原因的简化版本:
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
function getUser() {
let user = getCookie('ds_user')
if (!user) {
return null
}
return JSON.parse(atob(user))
}
const mockUser = {
user: {
id: "1671",
email: "artvandalay@industries.com",
username: "art",
firstName: "Art",
lastName: "Vandalay",
phone: null,
admin: true,
title: "",
guid: "u0000ZDCF4",
vendorUser: false,
lastLogin: "2019-06-07 18:52:11",
defaultStoreId: "6",
},
store: {
storeId: 6,
name: "Demo Store",
marketId: 13
}
}
setCookie('ds_user', JSON.stringify(btoa(mockUser)), 7)
console.log(getUser())
My fiddle: https://jsfiddle.net/u1zjsqyn/ 我的小提琴: https : //jsfiddle.net/u1zjsqyn/
I have tried following other solutions from similar posts like https://stackoverflow.com/a/9786592/5025769 , but no luck 我尝试过类似帖子中的其他解决方案,如https://stackoverflow.com/a/9786592/5025769 ,但没有运气
mockUser
is an object, when you do btoa(mockUser)
you end up with [Object, object]
, the string version of any object, as btoa
can't parse objects. mockUser
是一个对象,当你执行btoa(mockUser)
你最终得到[Object, object]
,任何对象的字符串版本,因为btoa
无法解析对象。
You want to stringify the object before converting to Base64, then when you get the data back, you do what you're doing, decode Base64 first, then parse as object. 您希望在转换为Base64之前对对象进行字符串化,然后当您获得数据时,执行您正在执行的操作,首先解码Base64,然后解析为对象。
setCookie('ds_user', btoa(JSON.stringify(mockUser)), 7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.