Res.render Failed to Lookup views/pug/index.pug

What’s happening:
res.render fails to lookup views/pug/index.pug. I tried views/pug and views/pug/index.pug both of which failed.

My code so far

"use strict";
require("dotenv").config();
const express = require("express");
const myDB = require("./connection");
const fccTesting = require("./freeCodeCamp/fcctesting.js");

const app = express();

fccTesting(app); //For FCC testing purposes
app.use("/public", express.static(process.cwd() + "/public"));

app.set("view engine", "pug");

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

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

What do I have wrong here? What am I missing? Thanks in advance for any help.
My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Edg/89.0.774.77.

Challenge: Set up a Template Engine

Link to the challenge:

From the Express.js docs

To render template files, set the following application setting properties, set in app.js in the default app created by the generator:

  • views , the directory where the template files are located. Eg: app.set('views', './views') . This defaults to the views directory in the application root directory.
  • view engine , the template engine to use. For example, to use the Pug template engine: app.set('view engine', 'pug') .

The relevant part for your case is:

This defaults to the views directory in the application root directory.

Since app.set('views', './views') wasn’t explicitly set in the server.js file, Express just uses the views directory in the root of your project.

To render a view, you don’t need to specify the views directory as Express is using it as the default in your case, so you only need to specify the file path relative to the views directory, which is pug/index.pug, but since the view engine property is set, you don’t need to specify the file extension, so pug/index would be adequate.

So I needed to do this:

app.set("view engine", "pug");
app.set("views", "./views");

and:

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

I didn’t have the second call to app.set and that’s why it was failing. Thanks for the help.

Actually, you could remove app.set("views", "./views") if you wanted to, and it would still work. As I mentioned, Express will use the views folder in your project root by default.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.