//加密
encodeBase64(rawString) {
if (rawString === null || rawString === '') {
return ''; // 将空值转换为空字符串
}
try {
const encodedString = btoa(rawString);
return encodedString;
} catch (error) {
return rawString; // 编码失败时返回原始值
}
},
这是前端加密的方法, 当rawString中包含中文时就会报错。
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
这是因为 btoa()
函数要求其输入是有效的 ASCII 字符序列,而中文字符不在 ASCII 字符集中。
解决方法:
用第三方库,如 Buffer
类
const Buffer = require('buffer').Buffer;
function encodeBase64(rawString) {
if (rawString === null || rawString === '') {
return '';
}
try {
const encodedString = Buffer.from(rawString, 'utf8').toString('base64');
return encodedString;
} catch (error) {
return rawString; // 编码失败时返回原始值
}
}