【问题标题】:How to avoid that JSON.stringify and JSON.parse replace a string?如何避免 JSON.stringify 和 JSON.parse 替换字符串?
【发布时间】:2021-08-16 08:10:38
【问题描述】:

我一直在使用 JSON.stringifyJSON.parse 将渲染的 html 放入 1 个字符串,替换该字符串中的某些内容,然后将所有内容解析回原始渲染的 html 格式。像这样:

res.render('system/error', { title: status.toString(), description: 'This is an error!', nonce: 'nonceValue' }, function(err, html) {
    html = JSON.stringify(html).replace("nonceValue", nonce);
    html = JSON.parse(html);
    res.send(html);
});

有谁知道是否有更简单的方法可以做到这一点? 我可以替换第一个 html 中的随机数吗?不用stringify吧?

【问题讨论】:

  • 你做的是模板引擎的功能,可以使用pugjs等专用的模板引擎,这里是expressjs.com/en/resources/template-engines.html
  • 我不介意,分享一些您的 JSON 数据示例。
  • 我不明白。根据documentationhtml 参数是一个字符串。那你为什么要打电话给JSON.stringify呢??
  • 使用正则表达式?但容易出错。

标签: javascript node.js json express


【解决方案1】:

实际上,这是可行的:

res.render('system/error', { title: status.toString(), description: 'This is an error!', nonce: 'nonceValue' }, function(err, html) {
    html = html.replace("nonceValue", nonce);
    res.send(html);
});

我这样写是因为 html 对象/字符串导致 Redis 和 set.ex() 函数出现问题。但是在这种用法中,它工作得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多