node.jsexpressejstemplating-engine

EJS file not loading after using express.static


I have some plain HTML/CSS files in my frontend folder and the ejs files in the views folder and every other ejs file loads perfectly but the index.ejs file I don't know what I am doing wrong here

This is my server.js: (this is a basic version of my server file)

const app = express();

app.set('views', __dirname + '/views');
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/frontend"));

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

//The below file loads perfectly. (requireAuth is a authentication middleware)
app.get("/create", requireAuth, (req, res) => {
  res.render("create");
});

Also both the files index.ejs and create.ejs are very similar

If anyone requires any extra details then they can comment down.


Solution

  • You've defined static middleware for / (root path) and the index page is also defined for root path, but because static middleware is defined early, express tries to find and return static file instead of rendering index page.

    You have two variants here:

    1. Define static middleware for some path different than root:
      app.use("/public", express.static(__dirname + "/frontend"));
    2. Don't use root path for index page: app.get("/index", (req, res)...