You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过res.render传递HTML元素?Node.js+EJS+Mongoose问题

解决EJS传递HTML字符串时的转义问题

问题根源在于你用了EJS的<%= htmlBody %>语法,这个语法会自动转义HTML特殊字符(比如把<转成&lt;),导致数据库里的原始HTML字符串被双重转义,最终出现&amp;lt;这类异常字符,DOMParser自然无法正确解析。

方案一:直接用EJS非转义输出(推荐)

不需要额外JS解析,直接让EJS把HTML字符串原样输出到页面,浏览器会自动解析成HTML元素,效率更高。

修改你的HTML页面代码:

<%- include("Header") -%>
  <!-- 用容器包裹内容,方便样式控制 -->
  <div class="blog-body">
    <%- htmlBody %>
  </div>
<%- include("Footer") -%>

这里的<%- %>是EJS的非转义输出语法,会直接把htmlBody里的HTML字符串插入到页面,不会做任何转义处理。

方案二:保留JS解析逻辑的处理方式

如果必须用DOMParser来处理,需要避免字符串转义和引号冲突问题:

  1. 先在路由里把HTML字符串转成JSON格式:
router.get("/blog/:id", (req, res)=>{
  Blog.find({_id: req.params.id}).then(arrayOfDocuments=>{
    if (arrayOfDocuments.length > 0){
      const htmlString = arrayOfDocuments[0].htmlContent;
      // 转成JSON字符串,避免引号冲突
      const safeHtml = JSON.stringify(htmlString);
      res.render("BlogPage", {
        metaDetails: {title: arrayOfDocuments[0].title}, 
        htmlBody: safeHtml
      });
    }else{
      res.render("Error");
    }
  })
})
  1. 然后在HTML页面里用非转义输出:
<%- include("Header") -%>
  <script>
    const parser = new DOMParser();
    // 用<%- %>输出JSON字符串,避免转义
    const html = parser.parseFromString(<%- htmlBody %>, "text/html");
    document.body.appendChild(html.body);
  </script>
<%- include("Footer") -%>

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:32:37