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

如何从EJS传递字符串到script标签?解决初始化访问报错

问题与解决方法

问题

尝试将EJS传递的字符串变量存入script标签并打印,出现报错:(index):19 Uncaught ReferenceError: Cannot access 'text' before initialization

相关代码:

Node.js 代码

app.get("/", (req, res)=> {
    res.render("index", {message: "hello world"})
})

HTML 代码

<script>
   const text = <% message %>
   console.log("message is " + text);
</script>

错误原因

EJS输出的字符串未被引号包裹,导致JS解析时把hello world当成未定义的变量名而非字符串值,触发引用错误。另外,原代码使用<% message %>不会输出变量值,EJS中需用<%= %>来输出变量内容。

解决方法

有两种可靠写法:

  1. 直接给输出字符串加引号,用<%= %>输出变量:
<script>
   const text = "<%= message %>";
   console.log("message is " + text);
</script>
  1. 用JSON.stringify处理变量(更适配含特殊字符的字符串),用<%- %>避免转义:
<script>
   const text = <%- JSON.stringify(message) %>;
   console.log("message is " + text);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:20:35