I've created a simple project, with 3 pages: Home, Contact and About.
Everything was working, then I wanted to add users registration with mongo.
So I followed this tutorial
But, when I add somes new routes, I can't acces any more pages.
This was my index.js when I can acces my 3 pages
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET contact page. */
router.get('/contact', function(req, res) {
res.render('contact');
});
/* POST contact page (submit). */
router.post('/contact', function(req, res) {
res.render('contact', { name: req.param('name') });
});
/* GET home page. */
router.get('/home', function(req, res) {
res.render('home');
});
/* POST home page (submit). */
router.post('/home', function(req, res) {
res.render('home', { comm: req.param('comm') });
});
/* GET about page. */
router.get('/about', function(req, res) {
res.render('about');
});
module.exports = router;
all simple and working.
and now, it's like that :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET contact page. */
router.get('/contact', function(req, res) {
res.render('contact');
});
/* POST contact page (submit). */
router.post('/contact', function(req, res) {
res.render('contact', { name: req.param('name') });
});
/* GET home page. */
router.get('/home', function(req, res) {
res.render('home');
});
/* POST home page (submit). */
router.post('/home', function(req, res) {
res.render('home', { comm: req.param('comm') });
});
/* GET about page. */
router.get('/about', function(req, res) {
res.render('about');
});
module.exports = router;
module.exports = function(passport){
// /* GET login page. */
// router.get('/', function(req, res) {
// // Display the Login page with any flash message, if any
// res.render('index', { message: req.flash('message') });
// });
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
return router;
}
and now, no routes are showed.
Any ideas ?
thanks !
EDIT : app.js
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 swig = require('swig');
var dbConfig = require('./db.js');
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url);
var routes = require('./routes/index');
var app = express();
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
// view cache
app.set('view cache', false);
swig.setDefaults({ cache: false });
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);
/// catch 404 and forwarding 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;
Your module expects a passport object
module.exports = function(passport){
but you're not calling it with a passport object in app.js
var routes = require('./routes/index');
also, you'll need to defined passport before calling the routes module. So in the end you'll need to modify your app.js to look something like this:
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
...
var routes = require('./routes/index')(passport);
...
app.use('/', routes);
Related
I am new to NodeJs and Express. I want to make an Ajax call from an ejs file :
<script>
$(document).ready(function() {
$.ajax({
async : false,
url: "/organisation/list",
success : function(data, status, xhr) {
alert("finsihed");
}
});
});
</script>
Here is the config of my app :
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 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);
// 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;
Here 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;
How to make it possible to reach the Ajax url /organisation/list ? Should I create another file in the routes directory ?
You can simply write a route like this :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET organisation list. */
router.get('/organisation/list', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
or you can create a separate file that handles all requests related to the organization.
app.js
app.use('/organization', require('./routes/organization.js');
routes/organization.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/list', function(req, res, next) {
//res.render('index', { title: 'Express' });
res.status(200).json([]);
});
module.exports = router;
I am working on a NodeJS app that has the login on a different domain / port.
In my case, I have the login server on localhost:3000 and the application on localhost:3001.
Since I am using PassportJS, when I go to localhost:3001/profile I check if the user is logged in using
function isLoggedIn(req, res, next)
{
if (req.isAuthenticated())
{
return next();
}
res.redirect('http://localhost:3000/login');
}
After login, I send and get an SMS code, I validate the code and then I get redirected back to http://localhost:3001/profile. The problem is, once back, I get redirected to the login server again.
app.post('/login', passport.authenticate('local-login',
{
successRedirect: '/sendsms',
failureRedirect: '/login',
failureFlash: true
}),
function (req, res)
{
if (req.body.remember)
{
req.session.cookie.maxAge = 1000 * 60 * 30;
}
else
{
req.session.cookie.expires = false;
}
});
From /sendsms I get redirected to /validate:
app.post('/validate', function (req, res)
{
console.log("SMS Code: " + req.body.smscode);
if (checkSMSCode(req.body.smscode, req.user))
{
console.log("OK");
res.redirect('http://localhost:3001/profile');
}
else
{
console.log("NOK");
res.redirect('/login');
}
});
This is the app.js on my authentication server:
'use strict';
var debug = require('debug');
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var helmet = require('helmet');
var request = require('request');
var connect = require('connect');
var app = express();
/*
* Connect to the database.
* Pass passport for configuration
*/
require('./config/passportHelper')(passport);
/*
* Setup the express application
*/
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(helmet());
// Setup ejs templating
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Setup passport sessions
app.use(session(
{
secret: 'mysecretkey',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
/*
* Setup the resources
*/
app.use('/css', express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/js', express.static(path.join(__dirname, 'public/scripts')));
/*
* Setup the routes
*/
require('./routes/index')(app);
require('./routes/login')(app);
require('./routes/signup')(app);
require('./routes/profile')(app);
require('./routes/logout')(app);
require('./routes/redirect')(app);
require('./routes/ticketing')(app);
require('./routes/object')(app);
require('./routes/sendsms')(app);
require('./routes/validate')(app);
/*
* Catch 404 and forward to error handler.
*/
app.use(function (req, res, next)
{
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/*
* Development error handler.
* Will print stacktrace.
*/
if (app.get('env') === 'development')
{
app.use(function (err, req, res, next)
{
res.status(err.status || 500);
console.log("ERROR");
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.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function ()
{
console.log('Express server listening on port ' + server.address().port);
debug('Express server listening on port ' + server.address().port);
});
I'm pretty sure I'm missing something very obvious, especially since it's the first time I am doing something like this (standalone authentication server) but I can't figure it out and I seem to be running around in circles.
At first, everything was designed as a single application and since /profile was on the same domain, there was no issue.
Any ideas or hints?
I am new to NodeJS and I am experiencing a problem while setting up my routes. I am using i18next, i18next-express-middleware and i18next-node-fs-backend in order to create a multilingual test website.
I would like my URL to look like the following depending on the selected language:
/fr/index, for french,
/en/index, for english,
/jp/index, for japanese.
I am currently facing at least one problem. The default route does not send me to the correct URL. I am always directed to /.
Here is my server.js file:
'use strict';
var debug = require('debug');
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 i18next = require('i18next');
var i18nextMiddleware = require('i18next-express-middleware');
var backend = require('i18next-node-fs-backend');
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', 'pug');
i18next
.use(backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
backend: {
loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json',
addPath: __dirname + '/locales/{{lng}}/{{ns}}.missing.json'
},
ns: ["ns.common"],
defaultNS: "ns.common",
fallbackNS: "ns.common",
fallbackLng: 'en',
preload: ['en', 'fr', 'jp'],
saveMissing: true,
removeLngFromUrl: false,
detection: {
order: ['path', 'session', 'querystring', 'cookie', 'header']
},
});
app.use(i18nextMiddleware.handle(i18next));
// 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: {}
});
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
Here is my index.js file:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/:lng', function (req, res) {
res.header("Content-Type", "text/html; charset=utf-8");
res.render('index', {});
});
module.exports = router;
The project is articulated as follows:
locales
|_en
ns.common.json
|_fr
ns.common.json
|_jp
ns.common.json
public
|_fonts
|_images
|_javascripts
|_stylesheets
routes
index.js
user.js
views
server.js
Everything is working fine if I enter manually the URL.
Can someone help me detect what is wrong in my code?
Thanks in advance for your answers.
Edit
As pointed out by Kishan, I use the following code, in order to redirect users to the correct locale. Thus, I am using a cookie to store the locale of a user. I ddo not know if it is a safe nor the most optimized way of doing things, but it works.
Here is the index file:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res) {
res.redirect(req.cookies.locale + '/index');
});
router.get('/:lng/index', function (req, res) {
res.header("Content-Type", "text/html; charset=utf-8");
res.render('index', {});
});
/* Change locale */
router.post('/locale', function (req, res) {
res.cookie('locale', req.body.locale, { maxAge: 900000, httpOnly: true });
res.json({ status: 'success', redirect: '/' + req.body.locale + '/index'});
});
module.exports = router;
You need to add a route for / (root) in the index.js.
In the above code, the route gets into index.js but not find the path for /(root).
So add the route like...
router.get('/', function (req, res) {
// YOUR LOGIC
});
in your index.js.
Am a newbie to Node.js, Am getting only a loading page in node.js post request when running the passport authentication. Can anyone help me
my Router.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user-model');
var Local = require('../config/passport-local');
/* GET home page. */
router.get('/', function(req, res, next){
res.render('index',{ title : 'Login'});
});
router.post('/login', (req, res, next) => {
passport.authenticate('local',(req, res,next) => {
console.log('ok');
});
}, (req, res, next) => {
});
module.exports = router;
passport-local.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user-model')
passport.use(new LocalStrategy(
function(username, password, next) {
console.log('auth');
User.findOne({username: username}, function(err, user) {
console.log('passport');
if(err) { return next(err);}
if(!user) {
return next(null, false, {message : 'invalid username'});
}
if(!user.validPassword(password)) {
return next(null, false, {message: 'invalid password'})
}
return next(null, user);
});
}
));
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commonKeys = require('./config/keys');
var app = express();
//connect mongoDb
mongoose.connect(commonKeys.mongoDB.connect + '/' + commonKeys.mongoDB.database, { useNewUrlParser: true });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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(flash());
app.use(passport.initialize());
app.use(passport.session());
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;
I am trying to learn passport authentication in nodejs. it is much appriciated if anyone can explain the error in this code and why its not working.
You need to update your code accordingly:
router.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.send('Done');
});
Here's more documentation.
I wanted to separate each group of routes in a file. I need to use isAuthenticated in most routes to restrict access. When I put all routes in the same file it works.
When I use module.exports = isAuthenticated in auth.js and in order.js I use var auth = require('auth.js'); I will get a error of 'isAuthenticated is not defined' when I go to http://localhost:3000/order the routes defined in auth.js just works as expected.
I'm using Express.js middleware 'Passport local strategy' (followed tutorial from tutsplus and downloaded github repository from here).
My project structure:
bin/www
models/auth/init.js
models/auth/user.js
models/auth/signup.js
models/auth/login.js
models/order.js
views/error.pug
views/index.pug
views/home.pug
views/layout.pug
views/order.pug
views/register.pug
routes/order.js
routes/auth.js
public/stylesheets/style.css
app.js
db.js
./routes/auth.js:
var express = require('express');
var router = express.Router();
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
module.exports = isAuthenticated;
module.exports = function(passport){
/* GET login page. */
router.get('/', function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
/* GET Home Page */
router.get('/home', isAuthenticated, function(req, res){
res.render('home', { user: req.user });
});
/* Handle Logout */
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
./routes/order.js:
var express = require('express');
var router = express.Router();
var order = require('../models/order');
var auth = require('./auth.js');
module.exports = function(passport){
router.get('/order', isAuthenticated, function(req, res){
res.render('order');
});
router.post('/order', isAuthenticated, function(req, res)
{
var testorder = new order({
orderid: '52363',
productname: 'it works',
quantity: 1337
});
testorder.save(function (err) {
if (err) {console.log(err.stack);}
console.log('saving done...');
});
res.render('order', { product: req.body.productname });
});
};
./app.js
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 pug = require('pug');
var dbConfig = require('./db');
var mongoose = require('mongoose');
// Connect to DB
mongoose.connect(dbConfig.url);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// 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());
// Initialize Passport
var initPassport = require('./models/auth/init.js');
initPassport(passport);
var auth = require('./routes/auth')(passport);
var order = require('./routes/order');
app.use('/', auth);
app.use('/order', order);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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
});
});
}
module.exports = app;
Try auth.isAuntheticated(),
It should work that way.