First of all, I am using:
express-session#1.14.2
express#4.14.0
I am basically trying to get a login system working and when user logs in, I set session.isloggedin = true.
So this is my 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 index = require('./routes/index');
var portfolioRoute = require('./routes/portfolio');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// 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({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true,
maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.use('/', index);
app.use('/portfolio', portfolioRoute);
// 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;
The index.html contains the login form.
Next, my index.js
var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');
var sess;
/* GET home page. */
router.get('/', function (req, res) {
sess = req.session;
console.log("SESSION IS: " + sess.isLoggedIn);
if(sess.isLoggedIn) {
res.render('portfolio', { isLoggedIn: true })
} else {
res.render('index', { isLoggedIn: false })
}
})
//END ------------
if(global.GLB_PORTFOLIO === null) {
port.getPortfolio(null, function(err, result) {
global.GLB_PORTFOLIO = result;
});
}
// API Routes
//router.use('/api', router);
router.route('/api/login')
.post(api.postLogin)
router.route('/api/portfolio')
.post(api.postPortfolio)
.get(api.getPortfolio)
//END ------------
module.exports = router;
Next, my api.js:
var util = require('util');
const backend = require('./portfolio.js');
exports.postPortfolio = function(req,res) {
backend.insertPortFolio(req.body, function(err, result) {
res.json({ result: result, error:err });
});
}
exports.getPortfolio = function(req,res) {
backend.getPortfolio(req, function(err, result) {
global.GLB_PORTFOLIO = result;
res.json({ portfolio: result, error: err });
});
}
exports.postLogin = function(req,res) {
backend.findUserByEmail(req.body.email, function(err, result) {
console.log("API: SESSION IS: " + req.session.isLoggedIn);
if(err || result === null) {
req.session.isLoggedIn = false;
} else {
req.session.isLoggedIn = true;
}
req.session.save();
res.json({ user: result, error: err });
});
}
The session variable is always undefined even after the save(). What am I doing wrong?
Related
I have created a Node.JS REST API server, and tried to test it by sending a GET request on https://localhost:3443/public/images/logo.png that logo.png image exist and I can see it in the directory. But the Postman gives me Not Found 404 error message.
This is my imagesRouter.js:
const express = require('express');
const bodyParser = require('body-parser');
const Images = require('../models/images');
var authenticate = require('../authenticate');
const imagesRouter = express.Router();
const cors = require('./cors');
imagesRouter.use(bodyParser.json());
imagesRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } );
imagesRouter.route('/')
//.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Images.find({})
.then((images) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(images);
}, (err) => next(err))
.catch((err) => next(err));
})
module.exports = imagesRouter;
And this is my app.js file:
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 usersRouter = require('./routes/usersRouter');
var imagesRouter = require('./routes/imagesRouter');
const uploadRouter = require('./routes/uploadRouter');
const Images = require('./models/images');
//const uploadRouter = require('./routes/uploadRouter');
//const favoriteRouter = require('./routes/favoriteRouter')
var config = require('./config');
const mongoose = require('mongoose');
//mongoose.set('useCreateIndex', true);
mongoose.Promise = require('bluebird');
var passport = require('passport');
var authenticate = require('./authenticate');
// Connection URL
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
//useMongoClient: true,
/* other options */
useNewUrlParser: true ,
useUnifiedTopology: true
});
connect.then((db) => {
console.log("Connected correctly to server");
}, (err) => { console.log(err); });
var app = express();
// Secure traffic only
app.all('*', (req, res, next) => {
if (req.secure) {
return next();
}
else {
res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
}
});
// 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(passport.initialize());
app.use('/', index);
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public/images',imagesRouter);
app.use('/imageUpload',uploadRouter);
//app.use('/imageUpload',uploadRouter);
//app.use('/favorites',favoriteRouter);
// 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;
EDIT: This is my app files tree:
You'll need to specify the base of the static router to point to the public folder. You are currently "mounting" the public folder on the root route in the current code. You can change this line
app.use(express.static(path.join(__dirname, 'public')));
To:
app.use('/public', express.static(path.join(__dirname, 'public')));
Alternatively, you can call the endpoint from postman (or any other client) as: https://localhost:3443/images/logo.png
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');
I am using Cassandra + Node.js to create an app, but I am receiving an error for this code:
C:\Users\userx\node-cassandra\app.js:44
app.post('/',new);
^
SyntaxError: Unexpected token )
at Module._compile (module.js:545:28)
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 helenus = require('helenus');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var pool = new helenus.ConnectionPool({
hosts : ['localhost:9160'],
keyspace : 'webinar',
cqlVersion : '3.0.0',
//user : 'test',
//password : 'test1233',
//timeout : 3000
//cqlVersion : '3.0.0' // specify this if you're using Cassandra 1.1 and want to use CQL 3
});
pool.connect(function(err){
if(err){
throw(err);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('cassandra',pool);
// 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.get('/', routes.index);
app.post('/', new);
app.delete('/', delete);;
// 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;
});
index.js
exports.index = function(req, res, next){
req.app.get('cassandra').cql('SELECT * FROM users LIMIT 10',function(err, users){
if(err){
return next(err);
}
res.render('index', { title: 'Users', users: users });
});
};
exports.new = function(req, res, next){
var insert = 'UPDATE users SET first_name=?, last_name=? WHERE email=?',
params = [req.body.first_name, req.body.last_name, req.body.email];
req.app.get('cassandra').cql(insert, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
exports.delete = function(req, res, next){
var remove = 'DELETE FROM users WHERE email=?',
params = [req.body.email];
req.app.get('cassandra').cql(remove, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
Error
SyntaxError: Unexpected token )
i just tried to change the app.post('/',routes.new);
but it showed inheritance mustnot be done
Please tell me where is my mistake
new is a reserved word in ECMAScript. I don't think you will be able to use it as a member name as it is being interpreted as creating a new object.
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.
I have this post login that stores an object in req.locals.user.
var router = express.Router();
var User = require('../models/user');
var Company = require('../models/company');
/* GET home page. */
router.get('/', function(req, res) {
res.render('users/login');
});
router.post('/users/login', function(req, res){
var email = req.body.email;
var password = req.body.password;
User.find({email: email, password: password}, function(err, user){
if(user.length == 0)
{
//user wasn't found
res.render('users/login', {validation: "Invalid Email Or Password"})
}
else
{
//user was found set session and local objects
req.session.user = user;
res.locals.user = user;
res.redirect('/dashboard');
}
});
});
my problem is that when I redirect the user to the dashboard. I get an error message saying that my object is undefined.
<h1 class="page-header">Dashboard v2 <small><%=user.firstName%>.</small></h1>
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 moment = require('moment');
var session = require('express-session');
var dashboard = require('./routes/dashboard');
var users = require('./routes/users');
var categories = require('./routes/categories');
var products = require('./routes/products');
var sales = require('./routes/sales');
var companies = require('./routes/companies');
var app = express();
// set locals
app.locals.moment = moment;
// 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(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({resave: true, saveUninitialized: true, secret:"mySecretString"}));
app.use(function(req,res,next){
res.locals.user = req.session.user;
delete req.session.user;
next();
}
app.use('/', dashboard);
app.use('/', users);
app.use('/', categories);
app.use('/', products);
app.use('/', sales);
app.use('/', companies);
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "api_key");
if(req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});
// 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
});
});
mongoose.connect('mongodb://localhost/test');
}
// 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;
How do I pass my object globally between my views ?
Problem because res.locals.user will be remove when you redirect (next request). Only req.session exists.
For set variable to next request. You need a middleware to set session to locals again
app.use(function(req,res,next){
res.locals.user = req.session.user;
delete req.session.user;
next();
});