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

ExpressJS首页首次加载返回200正常渲染,后续304返回未渲染EJS模板求助

Fixing the 304 Unrendered Index Page Issue in Express + EJS

Hey there, let's break down why your Express + EJS project is acting up with the homepage returning an unrendered index.html (304 status) after the first visit, while other pages work fine. This is almost always a browser caching conflict between your dynamic EJS render and static file handling. Here's how to fix it:

1. Check the Order of Your Routes and Static Middleware

Express processes middleware/routes in the order you define them. If you've set up express.static before your homepage route, the server will first look for a static index.html file in your public folder (if it exists) and return that instead of running your EJS render. Even if you don't have a static index.html, the browser might cache the initial response incorrectly.

Fix: Move your dynamic homepage route before the static middleware:

// First handle the dynamic homepage render
app.get('/', (req, res) => {
  res.render('index', { /* Your template data here */ });
});

// Then serve static files (css, js, images, etc.)
app.use(express.static('public'));

2. Disable Caching for the Dynamic Homepage

Since your homepage is dynamically rendered (it might change based on data), you need to tell browsers not to cache it. Add cache-control headers to your homepage route to force fresh requests every time:

app.get('/', (req, res) => {
  // Set headers to prevent browser caching
  res.set({
    'Cache-Control': 'no-store, no-cache, must-revalidate, private',
    'Pragma': 'no-cache',
    'Expires': '0'
  });
  res.render('index', { /* Your template data here */ });
});

This ensures the browser never reuses a cached version of the homepage and always asks the server for a fresh, rendered copy.

3. Remove Conflicting Static index.html Files

Double-check your static assets folder (usually public) to make sure there's no accidental index.html file sitting there. If there is, the server will prioritize that static file over your dynamic EJS route after the first cache hit. Delete it if it exists.

4. Verify with a Forced Refresh

To confirm it's a caching issue, press Ctrl + F5 (Windows/Linux) or Cmd + Shift + R (Mac) when reloading the homepage. If this loads the rendered EJS page correctly, you know the problem is indeed browser caching, and the fixes above will resolve it permanently.

Why do other pages work fine? Likely because they don't have a conflicting static file, and their routes are processed before static middleware, so browsers never get a chance to cache an unrendered version of them.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:18:53