将cookie的值设置为模板文字?
我正在创build一个模板文字,如下所示:
const someVar = 'hello' const str = ` Some random multiline string with string interpolation: ${someVar} `
然后在我的Koa应用程序中,我正在做:
this.cookies.set('str', str)
显然它不喜欢多行string,因为它给出了这个错误:
TypeError:参数值无效
有没有办法解决? 保持空白格式对我来说是非常必要的。
这与模板文字无关; 当你得到错误的时候,你有一个带有换行符的string。 你不能有一个cookie值的换行符。
可能保留这些换行符的最好方法是使用JSON:
this.cookies.set('str', JSON.stringify(str));
当然,你需要使用JSON.parse
它时使用它。
当然你不必使用JSON; 你可以使用URI编码:
this.cookies.set('str', encodeURIComponent(str));
…然后使用decodeURIComponent
(或任何消耗string的等价物)将其解码。