Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 设置cookie';将值转换为模板文本?_Javascript_Node.js_Cookies_Ecmascript 6_Template Literals - Fatal编程技术网

Javascript 设置cookie';将值转换为模板文本?

Javascript 设置cookie';将值转换为模板文本?,javascript,node.js,cookies,ecmascript-6,template-literals,Javascript,Node.js,Cookies,Ecmascript 6,Template Literals,我正在创建一个模板文字,如下所示: const someVar = 'hello' const str = ` Some random multiline string with string interpolation: ${someVar} ` 然后在我的膝关节炎应用程序中,我做的是: this.cookies.set('str', str) 显然,它不喜欢多行字符串,因为它会出现以下错误: TypeError:参数值无效 这有什么办法吗?在我的例子中,保留空白格式是非

我正在创建一个模板文字,如下所示:

const someVar = 'hello'    

const str = `
  Some random
  multiline string with string interpolation: ${someVar}
`

然后在我的膝关节炎应用程序中,我做的是:

this.cookies.set('str', str)
显然,它不喜欢多行字符串,因为它会出现以下错误:

TypeError:参数值无效


这有什么办法吗?在我的例子中,保留空白格式是非常必要的。

这与模板文本无关;当您得到错误时,您已经有了一个包含换行符的字符串。cookie值中不能有换行符

保留这些新行的最好方法可能是使用JSON:

this.cookies.set('str', JSON.stringify(str));
当然,在使用它时,您需要
JSON.parse

当然,您不必使用JSON;您可以使用URI编码:

this.cookies.set('str', encodeURIComponent(str));

…然后用
decodeURIComponent
(或任何消耗字符串的东西的等价物)对其进行解码。

啊,出于某种原因,我认为
JSON.parse
总是将字符串解析为对象/数组文本。我错了,非常感谢@saadq:你这么想是有原因的。:-)JSON规范的早期版本确实要求顶层为对象或数组。但很早以前就很清楚,允许任何有效的JSON值都更有用,这就是JavaScript规范(以及最终的JSON规范)的用武之地。已经有好几年了,但是顶层必须是一个物体或阵列的想法已经在人们的思维中确立,你仍然会发现人们在说。。。