Gonsa02
Gonsa02

Reputation: 351

Failed to lookup view "index.pug" in views directory

I'm trying to render a index.pug with nodejs server but it doesn't work. The index.pug is in the subdirectory /public/views. This is the code:

import express from 'express';
const app = express();
import path from 'path';
import { sequelize } from './db/db.js';

// SERVER CONFIGURATION
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Listening at ${PORT}`);
  sequelize.sync({ force: false })
    .then(() => console.log('Database Connected!'))
    .catch(err => console.log(err));
});

// VIEW SETTINGS
app.use('/public', express.static(import.meta.url + "/public"));
app.set("view engine", "pug");
// app.engine('html', require('ejs').renderFile);
app.set('views', path.join(import.meta.url, "../public/views"));

// BODYPARSER
app.use(express.urlencoded({ extended: false }));
app.use(express.json());


const routerHome = express.Router();

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

app.use(routerHome);

One thing that couldn't work is that when I do import.meta.url, it imports all_directories/app.js and then maybe express.static(import.meta.url + "/public") will be all_directories/app.js/public which doesn't exists.

If anyone knows what's happening I would be very grateful for you to help me.

The error I get is the following:

Error: Failed to lookup view "index.pug" in views directory "file:/home/marc/Disco/Projects/Gym/public/views"

Upvotes: 0

Views: 905

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

In the error message: Failed to lookup view "index.pug" in views directory "file:/home/marc/Disco/Projects/Gym/public/views", the directory start by file:/ which is strange, the correct path should be /home/marc/Disco/Projects/Gym/public/views.

I think you shouldn't mix up the file URL and file path. If you have your views file in /public/views subdirectory and static files in /public subdirectory, the view configuration should be changed from :

// VIEW SETTINGS
app.use('/public', express.static(import.meta.url + "/public"));
app.set("view engine", "pug");
// app.engine('html', require('ejs').renderFile);
app.set('views', path.join(import.meta.url, "../public/views"));

to :

// VIEW SETTINGS
app.use('/public', express.static("public")); // serve static files in public subdirectory under /public virtual path
app.set("view engine", "pug");
app.set('views', path.join(__dirname, "./public/views")); // use pug templates file in /public/views subdirectory

Upvotes: 1

Related Questions