express.js: show toastr message - node.js

I'm trying to get Toastr library to work in my ExpressJS app! I scaffolded the app with the yeoman 'standard' Express Generator...
I've required the lib express-toastr and did the following:
in app.js:
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const toastr = require('express-toastr');
app.use(cookieParser());
app.use(session( {secret: 'xxx', saveUninitialized: true, resave: true} ));
app.use(flash());
app.use(toastr());
in index.js
const express = require('express');
const router = express.Router();
const httpntlm = require('httpntlm');
router.post('/', function (req, res, next) {
// parse inputs
let user = req.body.user || "";
let password = req.body.password || "";
// save in session
req.session.user = {user: user, password: password};
// appropriate response to login attempt
if (!req.session.user) {
res.status(401).send();
}
else {
req.toastr.success('Successfully logged in.', "You're in!");
res.render('groups', {
req: req
});
}
});
module.exports = router;
In index.jade
#{req.toastr.render()}
I'm loading these files in my <head> section:
link(rel='stylesheet', href='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/css/toastr.min.css')
script(src='/components/jquery/dist/jquery.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js')
Nothing is showing. What am I missing???
-- UPDATE! --
Here is my complete app.js file. I now try to use express-flash and making a dedicated route for showing a flash message. Still not working. Please help!
'use strict';
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressSanitizer = require('express-sanitizer');
const login = require('./routes/login');
const apply = require('./routes/apply');
const admin = require('./routes/admin');
var session = require('express-session');
var flash = require('express-flash');
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(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(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: 'true',
secret: 'secret'
}));
app.use(flash());
// Route that creates a flash message using the express-flash module
app.all('/express-flash', function( req, res ) {
req.flash('success', 'This is a flash message using the express-flash module.');
res.redirect(301, '/');
});
// sanitize inputs
app.use(expressSanitizer());
app.use('/', apply);
app.use('/apply', apply);
app.use('/login', login);
app.use('/admin', admin);
// 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;

Try using this middleware in your app.js, I found this here
app.use(function (req, res, next)
{
res.locals.toasts = req.toastr.render()
next()
});
and then access locals in your view as follows:
#{toasts}
This worked for me.

So I am not familiar with your syntax in your index.jade file(!=). What does it do? If you change that line in your index to #{req.toastr.render()} it should work.

Related

i18n cannot use localization url

I am trying to add localization to my website. I install i18n, create 2 localization json files in spanish and english and I add the configuration in app.js file. The app.js file is this:
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 i18n = require("i18n");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var request = require('request');
var flash = require('express-flash');
var winston = require('winston');
winston.add(winston.transports.File, { name: 'app-info', maxFiles: 3, filename: 'logs/app-info.log', level: 'info' });
winston.add(winston.transports.File, { name: 'app-error', maxFiles: 3, filename: 'logs/app-error.log', level: 'error' });
require('dotenv').config();
var app_port = process.env.APP_PORT;
var fs = require('fs');
var app = express();
app.listen(app_port, function(){
console.log('listening on *:' + app_port);
});
// Include php notifications
var notifications = require('./phpmonitor');
// Define routes
var routes = require('./routes/index');
var login = require('./routes/login');
var doctors = require('./routes/doctors');
var new_appointment = require('./routes/new_appointment');
var new_appointment_medicine = require('./routes/new_appointment_medicine');
var new_appointment_psychology = require('./routes/new_appointment_psychology');
var appointments = require('./routes/appointments');
var videoconference = require('./routes/videoconference');
var user = require('./routes/user');
var user_doctor = require('./routes/user_doctor');
var doctor = require('./routes/doctor');
var history = require('./routes/history');
var public = require('./routes/public');
var ajax = require('./routes/ajax');
var patients = require('./routes/patients');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// i18n setup
i18n.configure({
locales:['es', 'en'],
defaultLocale: 'es',
objectNotation : true,
queryParameter: 'lang',
cookie: 'i18n',
syncFiles: true,
updateFiles: true,
directory: __dirname + '/locales'
});
// 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(flash());
app.use(i18n.init);
app.locals.request = request.defaults({jar: true});
app.locals.winston = winston;
// Set session
app.use(session({
store: new RedisStore,
secret: 'Y0V3NJS58jP61lfQjPn8gm99Cb2Ppl6y',
resave: true,
saveUninitialized: false,
}));
// Global use, set locale and basic locals
app.use(function(req, res, next) {
var cookie = req.cookies.i18n;
if (cookie === undefined) {
res.cookie('i18n', 'es', { maxAge: 900000000, httpOnly: true });
}
// Wizard cookie
var cookie_wizard = req.cookies.omnidoctor_wizard;
if (cookie_wizard === undefined) {
res.locals.wizard_cookies = 'pending';
}
// Accept cookies
var accept_cookies = req.cookies.omnidoctor_cookies;
if (accept_cookies === undefined) {
res.locals.accept_cookies = 'pending';
}
i18n.setLocale(req, i18n.getLocale());
app.locals.api = process.env.API_URL;
app.locals.site_url = process.env.SITE_URL;
app.locals.site_protocol = process.env.SITE_PROTOCOL;
app.locals.socket_port = process.env.SOCKET_PORT;
res.locals.analytics = process.env.ANALYTICS;
// Load moment with i18n locale
app.locals.moment = require('moment');
app.locals.moment.locale(i18n.getLocale());
next();
});
app.use('/', routes);
app.use('/', login);
app.use('/doctors', doctors);
app.use('/history', history);
app.use('/new-appointment/medicine', new_appointment_medicine);
app.use(['/new-appointment/psychiatry', '/new-appointment/psychology'], new_appointment_psychology);
app.use('/new-appointment', new_appointment);
app.use('/appointments', appointments);
app.use('/videoconference', videoconference);
app.use('/', user);
app.use('/', user_doctor);
app.use('/', public);
app.use('/doctor', doctor);
app.use('/ajax', ajax);
app.use('/patients', patients);
// 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: {}
});
});
/*app.listen(3500, function () {
console.log("express has started on port 3500");
});*/
module.exports = app;
I want to make it work when I write the url mywebsite.com/en or mywebsite.com/en but it doesn't find them I tried to follow this documentation:
https://www.npmjs.com/package/i18n
and look in diferent forums but none of the solutions worked for me. What is missing to make it work properly? I saw that the routes have to be modified but I try that as well and it did't work.
EDIT
I changed a bit the app.js file following another tutorial that I saw in the web. Now When I go to mywebsite.com/en it works perfectly but when I go to mywebsite.com/es it does't translate it.
So if I have this in es.json file translation:
{
login:{
title: "Bienvenido"
}
}
When I go to mywebsite.com/es there will appear login.title
In the router/index.js I have this:
router.get('/', requireLogin, function(req, res, next) {
request = req.app.locals.request;
res.setLocale(req.cookies.i18n);
if( req.session.role == 'doctor' ) {
var locals = {
i18n: res
};
res.render('index', locals);
}
});
router.get('/es', function (req, res) {
res.cookie('i18n', 'es');
res.redirect('/')
});
router.get('/en', function (req, res) {
res.cookie('i18n', 'en');
res.redirect('/')
});
You configured it well so i guess your issue is in the use on the i18n library, the problem is that you didn't shared it.
I would recommand going over this tuturial:
https://www.sitepoint.com/how-to-implement-internationalization-i18n-in-javascript
And making sure you use the lirary in the right way, for exmple if you what to write a headline use it as such:
var headline = i18n.__('Main Headline');

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;

Browser doesn't show index page made by index.js and index.jade on Node.js

I'd like to show index page by index.js and index.jade on Node.js, however browser returns the page only show index.html as attached picture.
I set the index.js as routes as following, thus I think the root path should return index page.
var routes = require('./routes/index');
app.use('/', sessionCheck, routes);
The following is my present code. Could you tell me what is the problem?
###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 session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 30 * 60 * 1000 // 30min.
}
}));
var sessionCheck = function(req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/login');
}
};
app.use('/login', login);
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;
###routes/index.js
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;
###views/index.jade
extends layout
block content
h1= title
p Welcome to #{title}
I've found the problem.
Becuase I set the root directory '/public', I could not access index.js.Thank you for you kindeness.
app.use(express.static(path.join(__dirname, 'public')));

Trouble with Express 4 and CSRF Token posting

I think I'm misunderstanding how the token is supposed to post. I'm just getting a 403 every time, even though it's actually attempting to pass the token.
Here's the server code
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 redis = require('redis');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var ejs = require('ejs');
var csrf = require('csurf');
var util = require('./public/javascripts/utilities');
var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var loginProcess = require('./public/javascripts/login.js').loginProcess;
// var loginProcess = require('./public/javascripts/login.js')
var client = redis.createClient();
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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, '/public')));
app.use(cookieParser('secret'));
app.use(session(
{
store: new RedisStore({ host: 'localhost', port: 6379, client: client }),
secret: 'secret',
saveUninitialized: true,
resave: false
}
));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(csrf());
app.use(util.csrf);
app.use(util.authenticated);
app.use('/', routes);
app.use('/users', users);
app.use('/login',
login,
loginProcess);
// 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;
The login route is
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('login', {title: 'Login'});
next();
});
Here is what I've got in var util
module.exports.csrf = function csrf(req, res, next){
res.locals.csrftoken = req.csrfToken();
next();
};
I'm also using ejs, and have this after my form method='post'
<input type="hidden" name="_csrf" value="<%= csrfToken %>>"
Whenever it returns 403, the form data is at least getting the name of the input
_csrf:
username:Test
password:>9000
But as you can see, it's blank
I also wasn't sure if the res.locals.csrftoken was being passed to the login route, so I also tried adding it directly there with a router.post, but got this error
Error: Can't set headers after they are sent.
I've gone through nearly every post concerning this I could find. I'm either not making the logical connection for what I'm missing, or am wholly misunderstanding something. Both are entirely plausible, my money is on the second one. Feel free to make any, why in the world are you doing that - that way - comments, because chances are I'm doing it out of ignorance, and those comments are good for the learning process. Thanks in advance.
edit: Removing my utility function and following correct 'csurf' docs successfully passed the csrf token to my /login view.
I'm getting closer, still wrong, but this may shed some light as to where I'm getting confused.
var express = require('express');
var router = express.Router();
/* GET login listing. */
router.get('/', function(req, res, next) {
res.render('login', {title: 'Login', csrfToken: req.csrfToken() });
});
function loginProcess(req, res, next){
console.log(req.body);
res.send(req.body.username + ' ' + req.body.password);
res.json(req.csrfToken());
next();
};
router.post('/', loginProcess);
module.exports = router;
Why would this redirect me to a 404 page?
Because I didn't remove my authentication step before testing.
Also, I know this is sending un & pw in plain text along with the csrf token and that's no bueno. I'll get to that eventually.
Something I did is attempting to set headers when submitting username and password.
Error: Can't set headers after they are sent.
I thought it was my loginProcess function, but removing next(), or adding res.end(); didn't help
function loginProcess(req, res, next){
console.log(req.body);
res.send(req.body.username + ' ' + req.body.password);
res.json(req.csrfToken());
res.end();
};
edit You can't use res.send and res.json like that because they're both technically sending, and you can't send headers+body and then send headers+body again.
The token is automatically sent so I removed res.json(req.csrfToken();
But somewhere I'm not redirecting correctly on post. I'm just getting a blank page with the username and passwords that were entered.
edit:
Hokay. So everything appears to be working properly. Here is the updated code.
login.js
var express = require('express');
var router = express.Router();
/* GET login listing. */
router.get('/', function(req, res, next) {
res.render('login', {title: 'Login', csrfToken: req.csrfToken() });
});
function loginProcess(req, res, next){
var isAuth = auth(req.body.username, req.body.password, req.session)
if (isAuth){
res.redirect('/chat');
}else{
res.redirect('/login');
}
};
router.post('/', loginProcess);
router.get('/logout', out);
module.exports = router;
app.js
var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var chat = require('./routes/chat');
//var loginProcess = require('./public/javascripts/login.js').loginProcess;
var client = redis.createClient();
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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, '/public')));
app.use(cookieParser('secret'));
app.use(session(
{
secret: 'secret',
store: new RedisStore({ host: 'localhost', port: 6379, client: client }),
saveUninitialized: true,
resave: false
}
));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(csrf({ cookie: true }));
// app.use(util.csrf);
app.use(util.authenticated);
app.use('/', routes);
app.use('/users', users);
app.use('/login', login);
app.use('/chat', [util.requireAuthentication], chat);
I've still got a ton of cleanup, but it's at least functional.
Much thanks to #Swaraj Giri
What is app.use(util.csrf);? Guess you need to remove it.
From the docs of csurf,
You need to set csrf({ cookie: true }). This sets the crsf value in req.body._csrf.
Then you need to pass { csrfToken: req.csrfToken() } to the view of login page.
In login.js
router.get('/', function(req, res, next) {
res.render('login', {title: 'Login', csrfToken: req.csrfToken()});
next();
});

can no longer load express app webpages

So i've been working on getting a user authentication system going and then I encountered a problem where my webpages would no longer load. npm start works fine and the server appears to be running. going to localhost just shows that the bar keeps loading and never eventually loads (before the webpages loaded instantly). I have no idea what I changed but tried to revert as much of the code to the original but still no dice. let me know if any other files are needed. thanks in advance
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 mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
// var users = require('./routes/users');
var routes = require('./routes/index');
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('ground glass'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(flash);
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use('/', routes);
//app.use('/users', users);
// passport config
// var Account = require('./models/accounts');
//passport.use(new LocalStrategy(Account.authenticate()));
//passport.serializeUser(Account.serializeUser());
//passport.deserializeUser(Account.deserializeUser());
// mongoose
//mongoose.connect('mongodb://localhost/test');
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
//var flash = require('connect-flash');
//app.use(flash());
//require('./routes/index')(app);
/*
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));*/
// 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;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'test' });
});
module.exports = router;

Resources