'Express dev environment error: Failed to lookup view "pages/index" in views directory

I'm getting this error both in the browser and on the terminal while trying to access my development environment:

Error: Failed to lookup view "pages/index" in views directory "/home/juan/dev/my-project/lib/views" at Function.render (/home/juan/dev/my-project/node_modules/express/lib/application.js:583:17) at ServerResponse.render (/home/juan/dev/my-project/node_modules/express/lib/response.js:1017:7) at file:///home/juan/dev/my-project/lib/index.js:15:31 at Layer.handle [as handle_request] (/home/juan/dev/my-project/node_modules/express/lib/router/layer.js:95:5) at next (/home/juan/dev/my-project/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/juan/dev/my-project/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/juan/dev/my-project/node_modules/express/lib/router/layer.js:95:5) at /home/juan/dev/my-project/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/juan/dev/my-project/node_modules/express/lib/router/index.js:341:12) at next (/home/juan/dev/my-project/node_modules/express/lib/router/index.js:275:10)

/home/juan/dev/my-project/lib/index.js:

import _ from 'lodash';
import express from 'express';
import path from 'path';
import {engine} from 'express-handlebars';

const PORT = process.env.PORT || 5000;
const dirname = path.join(path.resolve(), 'lib');

let app = express();
app.engine('handlebars', engine({defaultlayout: 'index', extname: '.hbs'}));
app.use(express.static(path.join(dirname, 'views')));
app.set('view engine', 'handlebars');
app.set('views', path.join(dirname, 'views'));
app
  .get('/', (req, res) => res.render('pages/index'))
  .listen(PORT, () => console.log(`Listening on ${ PORT }`));

Does anyone know what's happening? Thank you in advance! :)



Solution 1:[1]

You have to register the engine under the same name you use for extname:

app.engine('.hbs', engine({ defaultlayout: 'index', extname: '.hbs' }));
app.set('view engine', '.hbs');

Otherwise, you'll get strange behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jabaa