Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up default view path in Express.js

Tags:

express

view

Source Code

app.js

var express = require('express');
var app = express();
var path = require('path');
var viewPath = path.join(__dirname, 'app/views');

app.set('views', viewPath);
app.set('view engine', 'jade');

app.get('/', function(req, res) {
    res.render('index', { title: 'Home Page' } );
});

app.listen(3000);

Folder Structure

app
└───views     
│        └───index.jade
└───app.js

Error in Browser

Error: Failed to lookup view index in views directory d:\Users\Admin\Documents\...\project\views

Question

I would like to structure my app by placing the view files in app/views/*.jade, but I cannot get it working so far, using app.set('views', ...) should work but it doesn't

console.log(viewPath) shows d:\Users\Admin\Documents\...\project\app\views

I also tried e.g. app.set('views', 'xxx') but the error still get stucked on the same path, it seems like app.set() has never been called, what's wrong here ?, please guide.

Thanks

Edit

It doesn't matter what I set using app.set('views', 'xxx') the error will always be Error: Failed to lookup view index in views directory d:\Users\Admin\Documents\...\project\views (always keep saying the same path)

I'm so sorry about router.get('/', ...), My actually project's files are different, so I was making mistake here

like image 405
Artisan Avatar asked Oct 28 '15 06:10

Artisan


People also ask

How to set default route in Express?

Steps to set the default route in the express app:Step 1: Create your project folder. Step 4: Require 'express' and set your all general routes as per the requirements of your application. Step 5: Below all routes, set your default route as shown below: app.

Where does express look for views by default?

Express will automatically look inside the views/ folder for template files. The res. render() method is used to render the view we pass it and send the HTML to the client.

How do I change the view folder in Express?

You can use the method set() to redefine express's default settings. app. set('views', path. join(__dirname, '/yourViewDirectory'));

What is the difference between app use and app get?

app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.


1 Answers

Try using

app.set('views', path.join(__dirname, 'views'));

Your app.js is in your app folder so I think

var viewPath = path.join(__dirname, 'app/views');

app.set('views', viewPath);

will look into app/app/views/ instead of app/views/ because of __dirname
__dirname is the directory in which the currently executing script resides.

like image 147
Rox Avatar answered Sep 23 '22 06:09

Rox