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

EJS模板变量未定义错误求助 - Express项目问题排查

Express+EJS待办清单:EJS变量未定义问题

问题描述

用Express+EJS开发待办清单项目,其余功能正常,但EJS模板中的<%= variable %>抛出variable is not defined错误。

EJS代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To-Do-List</title>
    <link rel="stylesheet" href="public\styles.css" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
      crossorigin="anonymous"
    />

    <script
      src="https://kit.fontawesome.com/20accab6ba.js"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <div
      class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center"
    >
      <div class="list-group">
        <form
          class="list-group-item d-flex gap-3 bg-body-tertiary"
          action="/submit"
          method="POST"
        >
          <span class="pt-1 form-checked-content">
            <span contenteditable="true" class="w-100" id="taskInput">
              <input
                type="text"
                id="task"
                name="task"
                placeholder="Enter your task"
              />
            </span>
            <small class="d-block text-body-secondary">
              <i
                class="fa-regular fa-clock bi me-1"
                width="1em"
                height="1em"
                style="color: #7a8290"
              ></i>
              <input type="time" id="time" name="time" />
            </small>
          </span>
          <%= variable %>

          <button class="btn btn-primary" type="submit">Submit</button>
        </form>
      </div>
    </div>
  </body>
</html>

服务端代码

import express from "express";
import bodyParser from 'body-parser';
import ejs from "ejs";

import { dirname } from "path";
import { fileURLToPath } from "url";

const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes(); 

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", (req,res) =>{
    res.render(`${__dirname}/views/index.ejs`);
});

app.post('/submit', (req, res) => {
    res.render(`${__dirname}/views/index.ejs`, 
    {
        variable : "Hi",
    })  
  });

app.listen(port, () => {
    console.log("Server started at port:" + port);
});

错误信息

ReferenceError: C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\views\index.ejs:26
24|
25|

<%= variable %>
Submit

29|
variable is not defined
at eval (eval at compile (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:673:12), :12:26)
at index (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:274:36)
at exports.renderFile [as engine] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\response.js:1039:7)
at file:///C:/Users/Niklaus/Desktop/Web%20Develepment%20Course/BackEnd/4.5%20Capstone%20Prject%20To-Do-List/index.js:19:9)
at Layer.handle [as handle_request] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\router\layer.js:95:5)

解决方案

问题根源:访问首页的GET /路由渲染模板时,没有传递variable变量,只有提交表单的POST /submit路由传了变量。EJS模板在渲染时找不到变量,所以报错。

有两种解决方式:

方式1:给GET路由传递默认变量

修改GET /的处理逻辑,添加默认的variable值(比如空字符串):

app.get("/", (req,res) =>{
    res.render(`${__dirname}/views/index.ejs`, { variable: "" });
});

方式2:在EJS模板中添加变量存在判断

在模板里先检查变量是否存在,再输出:

<% if (typeof variable !== 'undefined') { %>
    <%= variable %>
<% } %>

这两种方式都能避免模板渲染时出现变量未定义的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:25:55