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

移入静态文件至public目录后EJS文件无法渲染的技术求助

EJS渲染失效问题解决

问题场景

原本list.ejs文件可正常渲染,将index.html和CSS文件移入public目录,并在app.js中添加app.use(express.static("public"))代码后,EJS文件无法渲染。

相关代码

const express = require("express");
const https = require("https");
const app = express();

app.set("view engine", "ejs");
app.use(express.static("public"));

app.get("/", function(req, res){
  const today = new Date();
  const options = {
    week: 'long',
    year:'numeric',
    month:'long',
    day:'numeric'
  }
  let day = today.toLocaleDateString("en-US", options);
  res.render("list.ejs",{kindOfDay:day} );
});

app.listen(3000, function(){
  console.log("Server is up and running on Port 3000.");
});

文件结构

主目录
├── public
│   └── index.html
└── views
    └── list.ejs

问题原因

express.static中间件会优先匹配public目录下的静态文件,当访问根路径/时,服务器会直接返回public目录中的index.html,跳过了app.get("/")路由里的EJS渲染逻辑,导致EJS页面无法被渲染。

解决办法

  • 删除public目录下的index.html,这样访问/时会触发EJS渲染路由
  • 修改EJS渲染的路由路径,例如将app.get("/")改为app.get("/list"),之后访问http://localhost:3000/list即可查看EJS页面
  • 若需要保留index.html,可调整路由顺序,将EJS渲染路由放在express.static中间件之前,但这种方式不推荐,会破坏静态文件的常规访问逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:04:55