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

如何在EJS的script标签中访问Express传递的数组 解决JSON.stringify报错

解决方案

核心问题排查

  • 变量名不匹配:服务端调用res.render传递到模板的变量是coffepoints,但EJS脚本中错误使用了不存在的变量campgrounds做序列化,直接导致报错。
  • 你当前使用<%- %>非转义输出的语法是正确的,无需调整该输出逻辑。

修正后的客户端EJS代码

<script> 
    const coffepoints = <%- JSON.stringify(coffepoints) %>
</script>

特殊场景兼容(可选)

如果你的数据中包含</script>这类特殊字符串,可能会导致脚本标签被意外截断,可通过base64编码规避该问题:

  1. 服务端代码调整
module.exports.index = async (req, res) => {
    const coffepoints = await CoffePoint.find({});
    // 序列化后做base64编码再传递到模板
    res.render('coffepoints/index', { 
        coffepoints: Buffer.from(JSON.stringify(coffepoints)).toString('base64')
    })
}
  1. 客户端代码调整
<script> 
    // 解码后再反序列化得到原数组
    const coffepoints = JSON.parse(atob('<%- coffepoints %>'))
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:48:01