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

EJS模板无法渲染,请求技术协助(附代码与文件结构)

EJS模板无法正常渲染问题排查方案

以下是你提供的代码:

index.js

import express from "express";
import bodyParser from "body-parser";
import path from "path"; // 建议添加path模块用于路径处理

const app = express();
const port = 3000;

app.set("view engine", "ejs");
// 关键:如果你的index.ejs不在默认的views文件夹,需要指定模板目录
app.set('views', path.join(__dirname, '.')); // 假设ejs文件在根目录,或者改为'./views'如果放在views文件夹

app.use(bodyParser.urlencoded({ extended: true }));

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

app.post("/submit", (req, res) => {
  // 增加空值判断,避免未输入姓名时报错
  const firstName = req.body["fName"] || "";
  const lastName = req.body["lName"] || "";
  const numLetters = firstName.length + lastName.length;
  res.render("index.ejs", { numberOfLetters: numLetters });
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

index.ejs

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Name Letters</title>
</head>

<body>
  <h1>Write your name below</h1>
  <!-- 简化条件判断,直接使用变量名 -->
  <% if(numberOfLetters){ %>
    <h1>There are <%= numberOfLetters %> letters in your name.</h1>
  <% } %>
  <form action="/submit" method="POST">
    <input type="text" name="fName" placeholder="First name">
    <input type="text" name="lName" placeholder="Last name">
    <input type="submit" value="OK">
  </form>
</body>

</html>

核心问题排查与解决步骤:

  1. 模板目录配置错误
    Express默认会在项目根目录的views文件夹中查找模板文件。如果你的index.ejs直接放在根目录(而非views文件夹),必须显式指定模板路径:

    • 先导入path模块(已在修改后的index.js中添加)
    • 添加app.set('views', path.join(__dirname, '.'));指定模板目录为当前根目录
    • 或者直接将index.ejs移动到新建的views文件夹中,无需额外配置
  2. 依赖验证
    执行以下命令确保所有依赖正确安装且版本兼容:

npm install express ejs body-parser
npm list ejs

确认ejs已出现在依赖列表中,若版本差异过大,可尝试安装与之前正常项目相同的版本:

npm install ejs@x.x.x # 替换为之前项目的ejs版本号
  1. 模板语法与空值处理
  • EJS中可直接访问传入的变量,无需通过locals前缀,简化判断逻辑可避免潜在的隐式问题
  • 在处理表单提交时增加空值判断,避免用户未输入姓名时出现Cannot read properties of undefined (reading 'length')错误
  1. 服务器重启与缓存清理
    修改配置或代码后,务必重启Express服务器;同时清空浏览器缓存(快捷键Ctrl+Shift+R),避免加载旧的缓存内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:20:12