简体   繁体   English

对包含的JSON进行字符串化<script> tags

[英]Stringifying JSON that contains <script> tags

I'm trying to pass initial state from server to client by stringifying that state and storing it in global variable. 我试图通过初始化状态并将其存储在全局变量中来将初始状态从服务器传递到客户端。 Below is simplified version of what I'm doing. 以下是我正在做的简化版本。

// home.tsx
res.render('home', { appState: {script: '<script></script>'} });

// home.pug
doctype html
html
    head
        script.
            window.__initialState__ = !{JSON.stringify(appState)};
    body
        #root

Sadly the result looks like this 可悲的是结果看起来像这样

<script>window.__initialState__ = {"script":"<script></script>

which is not valid Javascript. 无效的Javascript。 My endgoal is to have server's appState object assigned to window.__initialState__. 我的最终目标是将服务器的appState对象分配给window .__ initialState__。

The 1st part of your code is very confusing. 您的代码的第一部分非常混乱。 However, as a general rule, you should always encode any HTML passed from the server to the client as string. 但是,作为一般规则,您应该始终将从服务器传递到客户端的所有HTML编码为字符串。

So you need to change the part of your server code that generated the line below: 因此,您需要更改服务器代码中生成以下行的部分:

let scriptObject = {script: '<script></script>'};

to this (assuming that you're using pug and node.js): 为此(假设您使用的是pug和node.js):

var htmlencode = require('htmlencode');
let scriptObject = {script: htmlencode.htmlEncode('<script></script>')};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM