Failed to lookup view in Express MVC - node.js

My express version is 4.13.1.
My express dir is that:
app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/user',require('./controllers'));
controllers/index.js
var express = require('express');
var router = module.exports = express.Router();
router.use('/signup', require('./signup'));
controllers/signup/index.js
var express = require('express');
var router = module.exports = express.Router();
router.get('/', function(req, res, next) {
res.render('signup', { title: 'Signup' });
});
Then use 'http://localhost:3000/user/signup/' in browser,throw Error:
I'm waiting online,thank you.

You should specify all directories which contain views, for example:
var views = [
path.join(__dirname, 'views'),
path.join(__dirname, 'controllers/signups/views')
];
app.set('views', views);

Related

failed to look up views

Here is my structure like
app.js
routes
index.js
views
partials
index.ejs
This is index.js in routes folder that is rendering the template called index.ejs form views folder
const express = require('express');
const router = express.Router();
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
router.get('/', (req, res) => {
res.render(path.join(__dirname, '../index'));
})
module.exports = router;
Error says Failed to lookup view "layout" in views directory
You have to set the views directory first in app.js:
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
router.get('/', (req, res) => {
res.render('index.ejs'));
})

routing problem in express.js with html and hbs view engine

router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
my app.js routing code
app.set('dist', path.join(__dirname, 'dist'));
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
my folder structure
root/dist/index.html
I cannot open this page on my first page
how can I open this page? Where is my mistake?
thank you for your help
You can use the method set() to redefine express's default settings.
app.set('views', path.join(__dirname, '/dist'));
Working Example
const express = require('express')
const path = require('path')
const app = express()
const port = 3000;
var indexRouter = require('./routes/index');
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, '/dist'));
// Set view engine
app.engine('html', require('hbs').__express);
app.set('view engine', 'html');
app.use('/', indexRouter);
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Inside Dist Folder Index' });
});
module.exports = router;

Why is app.engine not defaulting to layout.hbs as a default

I created a style format with the layout.hbs and notice that all of the pages are not sharing the same consistency in style. I have noticed that I did not declare an app. engine within the app.js. Next, I implemented the app.engine code to set the default layout that is implemented within the layout.hbs
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout'}));
An error occurred stating that the layout.hbs cannot be located. I implemented the code again as I noticed I did not direct the folders directories to the layout .hbs. So I implemented the code to
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout', layoutsDir:__dirname + '/app_server/views'}));
And the error has disappeared and the default layout structure that has been set to layout.hbs is only showing on the local server index and not the same throughout all of the controllers. I am not too sure what else I am missing
controller and routes code
var express = require('express');
var exphbs = require('express-handlebars');
var router = express.Router();
var ctrlCaribbeanIslands = require('../controllers/CaribbeanIslands')
/* GET home page. */
router.get('/', ctrlCaribbeanIslands.login);
router.get('/blog/add',ctrlCaribbeanIslands.addPost);
router.get('/chat/add',ctrlCaribbeanIslands.addChat);
router.get('/review/add',ctrlCaribbeanIslands.addReview);
router.get('/traceYourTravel', ctrlCaribbeanIslands.tracetravel);
**module.exports = router;**
//controller
module.exports.login = function (req, res) {
res.render('index', { title: 'login'});
};
module.exports.addPost = function(req, res){
res.render('index', { title: 'Add Post' });
};
module.exports.addChat = function(req, res){
res.render('index', { title: 'Add Chat' });
};
module.exports.addReview = function(req, res){
res.render('index', { title: 'Add Review' });
};
module.exports.tracetravel = function(req, res){
res.render('index', { title: 'Trace travel' });
};
app.js
var createError = require('http-errors');
var express = require('express');
var handlebars = require('hbs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require ('express-handlebars');
var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users');
var app = express();
app.engine('hbs', hbs ({extname: 'hbs',defaultLayout: 'layout', layoutsDir:__dirname + '/app_server/views'}));
app.set('views', path.join(__dirname, 'app_server','views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
#Zrushb Sorry, my bad, it's with app.set, not use. The code should look like this:
const express = require("express"),
hbs = require("hbs"),
mongoose = require("mongoose")
bodyParser = require("body-[arser")
var app = express()
//In ** your database if you need any
mongoose.connect("mongodb:localhost:27017/**")
app.set("view engine", "hbs")
//To get or post
app.set("view engine", "hbs") //Engine HBS
app.set("views", __dirname +"/views") //Folder views (templates)
app.use(express.static("public")) //Public is static (to get .js, images and .css)
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets'))); //Css folder specified (NOT WORKING)
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
app.use(bodyParser.json()) //Parser for JSON files
app.use(cookieParser())
hbs.registerPartials(__dirname+ "views/partials")
app.get("/" //etc)
app.post(//etc)
I think express no longer contains handlebars in it, I'd reccomend to download HBS with npm and then require it var hbs = require('hbs')
Then set the view engine to hbs like this -> app.use("view engine", "hbs")
Try that instead of requiring it from express-handlebars, it has worked for me so far.
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir:__dirname + '/app_server/views'
}));
change hbs to hbs.engine like this:
app.engine('hbs', hbs.engine({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir:__dirname + '/app_server/views'
}));
// view engine setup
(01)app.engine('hbs',hbs({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts/'}));
(02) app.set('views', path.join(__dirname, 'views'));
(03) app.set('view engine', 'hbs');
change (01) line like this (hbs to hbs.engine):
app.engine('hbs',hbs.engine({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts/'}));

Node.js , Express ejs views error

EJS Error: Failed to lookup view "admin_landing2" in views directory "/Users/aryanarora/Desktop/asn3/views".
while trying make a call to localhost/8080/yolo
I am getting the same error even if I switch to hbs. (i have installed both the packages)
var express = require("express");
var app = express();
var port = process.env.PORT || 8080;
var path = require('path');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var fs = require('fs');
// const hbs = require('hbs');
// hbs.registerPartials(__dirname + './views');
// app.set('view engine','hbs');
// Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
var users = [];
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', function(req,res,next){
console.log(req.method, 'request:', req.url);
next();
});
app.locals.yolo = require('./Data/courses.json');
//Request i am trying to get//
app.get('/yolo',function(req,res){
//res.sendFile(path.join(__dirname + '/admin_landing2.hbs'));
res.render('admin_landing2', {var1 : "pehla" , var2 : "dusra"});
});
app.get('/login', function(req,res){
res.sendFile(path.join(__dirname + '/admin_login.html'));
var filepath = './admin_login.html';
console.log(filepath);
});
The problem is that you're setting the views directory to the wrong location.
Do
app.set('views', __dirname)
instead of
app.set('views', path.join(__dirname, 'views'))

How to move route function to another js file in express.js?

I have the following code (app.js):
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.get('/api/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
Which works. What I'm going to do is to move the route (/api/:order) to another js file (routes/api.js). Here is the code:
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.use('/api', api);
The /routes/api.js file:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('respond with a resource');
});
// return all orders
router.get('/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
module.exports = router;
I got the following error:
TypeError: Cannot call method 'find' of undefined
Can anybody tell me what's wrong with my code? Thanks.
I assume req.collection is undefined, because app.param('orders') is not executed for the other router.

Resources