Express 4 with Handlebars add new Route - node.js

I am trying to add an "about" page to my new express app.
I am running express 4 with handlebars (hbs).
I have read through a number of tutorials but most don't go into adding a new route (or do but don't explain very well) I have been working from this tutorial primarily.
I need to know what to add to my app.js and my routes/ folder, I have about.hbs ready in views.
here is my app.js (generated by express generator):
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
and my routes/ folder contains index.js and users.js.
index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Sorry for simplicity of question, but I have spent 3 hours on this already and I feelit is probably a fairly easy thing to do.

I suggest you ditch the general default express generated application and create a proper routing system. Your app.js file should not contain routing, only environment variables. Here is the way I've setup my projects:
App.js
var express = require('express');
var http = require('http');
var path = require('path');
var compression = require('compression');
var app = module.exports = express();
var cacheTime = 86400000*7; //a week
//all environments
app.use(compression());
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('html', require('hogan-express'));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public',{ maxAge: cacheTime }));
//development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
require('./routes/index.js');
http.createServer(app).listen(app.get('port'), function(req,res){
console.log('Express server listening on port ' + app.get('port'));
});
The routes file:
var app = require('../app.js');
app.get('/Contact', function(req, res) {
res.render('contact.html', { /*object*/ });
});
//continue routes here
It's scalable and a viable option for large company projects. You may also split up the routes file into sepererate sections to organize better. Note: You will need to change some of my settings to your liking

Related

the command node bin\www results in module not found error

I am currently learning how to use nodejs alongside with express as well as ejs. I have a sample app.js file below
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
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;
As well as corresponding index.js files in a routes folder in the same directory as app.js. Below is the index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
I have already installed the missing packages by running npm install within the App folder that holds app.js, routes, views as well as other various folders. What am i doing wrong?

Post routes error in Express

I'm facing a problem every time I try to create a post route in Express.
I get a Not found error.
Everything was working well before and I don't know what is really happening
This is my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
And this is the users route:
users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Any help ?
Your code looks fine. Try to:
restart the app and make the post one again, check the logs. You may find an answer in the app logs . If still not working.
Verify the index path ./routes/index
If you still get not results . Reinstall the app again. Looks you are just starting so.

how to serve static files with nodejs in multiple routing

I am trying to make a website of my small bussiness of cables and wires
using nodejs express (ejs)
files are like:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
/* routes variables*/
var routes = require('./routes/index');
var cableWires = require('./routes/cableWires');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use(express.static('public/stylesheets'));
app.use(express.static('public/images'));
app.use(express.static('public/javascripts'));
/* routes */
app.use('/', routes); // index page
app.use('/cableWires', cableWires); //cables and wires
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
In routes/cablesWires.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('products_cableWires', { title: 'Umesh Electricals' });
});
router.get('/submersible_cables', function(req, res, next) {
res.render('submersible-cables', { title: 'Umesh Electricals' });
});
router.get('/house_wires', function(req, res, next) {
res.render('house-wires', { title: 'Umesh Electricals' });
});
module.exports = router;
When I go to cableWires page, everything is fine,
but when I go to house_wires page or submersible_cables page, it loads the content of ejs file but fails to load static files (css, javascript and images)
What could be the possible mistake am I doing
Its seems that when you make request to any route then it try to fetch that file from that URL path i.e - when you call /route1 then it will call the static file from relative path..so you have to change it to absolute path..
so change the static path and include "/" before static path
app.use(express.static('public')); app.use(express.static('/public/stylesheets')); app.use(express.static('/public/images')); app.use(express.static('/public/javascript
Let us know if its help

node express express.static prevents access from root path '/'

I am using express and I have a catch all route
router.use('*',function(){...});
and a root route
router.use('/', function(){...});
I have this route placed after the
app.use(express.static(path.join(__dirname, 'public')));
this causes my routes to not fire when placed below the previous line. however if I put my routes above it my catch all is also called on static asset requests. is there a way I can catch all requests except for the assets in my public folder including the route '/'? I don't want to resort to using regex and having to update it every time a directory is added to the public directory.
sorry for not being more details here are the relavant files
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
/* This is going to initialize the menubar for nwjs it is currently commented out as this is a non issue at this point
setTimeout(function () {
//initialize passport
var passport = require('./helpers/passport.js');
//setup routes
//setup window menu
console = window.console;
console.log(passport);
passport.init(app);
var gui = window.require('nw.gui');
var win = gui.Window.get();
var menu = new gui.Menu({
type: 'menubar'
});
menu.createMacBuiltin('jist', {
hideEdit: true,
hideWindow: true
});
gui.Window.get().menu = menu;
},1000);*/
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
//window.location.href="http://localhost:3000";
this is my index router
//routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.use('*', function(req, res, nex){
var path = req.originalPath;
if(~['/users/login', '/users/signup'].indexOf(path) || req.user) return next();
if(!req.user) return res.redirect('/users/login');
});
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

Issue while setting virtual host with node.js on express

I am building an application on node.js using Express. My application is running on port 3001. I want to set virtual host for my application so that when I use http://local.com:3001, it should lead me to my application's home page.
My node version is : v0.12.3
Express version : 4.12.4
NPM version : 2.9.1
I have added the host in /etc/hosts.
My application is at /var/www/local. I set up an express app under /var/www/vhost to act as vhost manager.After a lot of research, I tried using below two methods but none of them worked:
1) app.js of /var/www/vhost
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var vhost = require('vhost');
var app = express();
var main = express();
if (!module.parent) main.use(logger('dev'));
main.get('/', function(req, res){
res.send('Hello from main app!');
});
main.get('/:sub', function(req, res){
res.send('requested ' + req.params.sub);
});
// Redirect app
var redirect = express();
redirect.use(function(req, res){
if (!module.parent) console.log(req.vhost);
res.redirect('http://local.com:3001/' + req.vhost[0]);
});
// Vhost app
var app = module.exports = express();
app.use(vhost('*.local.com', redirect)); // Serves all subdomains via Redirect app
app.use(vhost('local.com', main)); // Serves top level domain via Main server app
if (!module.parent) {
app.listen(3001);
console.log('Express started on port 3001');
}
2) app.js of /var/www/vhost using express-vhost
var evh = require('express-vhost'),
express = require('express');
var appFactory = function(echo) {
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
return app;
};
var server = express();
server.use(evh.vhost(server.enabled('trust proxy')));
server.listen(3006);
evh.register('http://local.com:3001', appFactory('/var/www/local/app.js'));
Any suggestions if I am doing something wrong here or is there any other way to achieve the concept of virtual hosting with express on node.js would be really helpful. Thanks in advance :)

Resources