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/'}));
Related
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;
I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade
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'))
When I try to emit the 'ready' event from client on express.io, it shows an error that
{ route: [Function], broadcast: [Function] } 'req.io.route'
TypeError: Object # has no method 'ready
I am using express version express#4.12.4.
app.js is as shown below
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express.io')();
app.http().io();
//var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
and the index.js file is as below
app = require('express.io')()
app.http().io()
var router = app.Router();
/* GET home page. */
router.all('/', function(req, res, next) {
res.render('index', { title: 'Express' });
req.io.route('ready', function(res) {
console.log('tested..........');
})
});
module.exports = router;
client side code is as below
<script>
var socket;
$(document).ready(function(){
socket=io.connect(window.location.hostname);
socket.emit('ready');
});
</script>
</html>
please help me regarding this...
The router isn't a method on the return value of the constructor, it's exported with the module.
var express = require('express.io');
var app = express();
app.http().io()
var router = express.Router();
Also app.http().io() only needs to be called once, so remove it from your routes file.
Try
/* GET home page. */
router.all('/', function(req, res, next) {
app.io.route('ready', function(res) { //not req.io...
console.log('tested..........');
})
res.render('index', { title: 'Express' });
});
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.