I need to validate non-empty fields for a login (post request), but I get this error:
TypeError: req.checkBody is not a function
at D:\IDoo projects\ExpressGenerado\config\routes.js:76:9
This is my route file:
app.post('/login',function(req,res){
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('signup',{message: req.flash('loginMessage')});
}
else{
passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})(req,res);
}
});
And my entry point app file, after adding app.use(expressValidator) my web hangs up and doesn't validate, it does nothing:
var express = require('express');
var expressValidator = require ('express-validator');
var app = express();
var multer = require('multer')
var constants = require('constants');
var constant = require('./config/constants');
var port = process.env.PORT || 8042;
var passport = require('passport');
var flash = require('connect-flash');
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var dateFormat = require('dateformat');
var now = new Date();
app.use(expressValidator);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
require('./config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'ejs');
app.use(session({ secret: 'zomaareenstukjetekstDatjenietzomaarbedenkt' }));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./config/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.listen(port);
console.log('The magic happens on port ' + port);
You're doing this:
app.use(expressValidator);
However, expressValidator is a function that returns a middleware function, so you need to use it like this:
app.use(expressValidator());
Related
Using csurf, I am trying to integrate csrf protection into my node.js express 4 application. This is my code:
EDIT: The code below was updated according to the solution I found.
"use strict";
var http = require('http');
var https = require('https');
var port = process.env.PORT || 80,
express = require('express'),
csrf = require('csurf'),
bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy,
csrfProtection = csrf({ cookie: true }),
mongoose = require('mongoose'),
conn = mongoose.createConnection('foo'),
cookieParser = require('cookie-parser'),
passport = require('passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
app = express();
app.set('view engine', 'ejs');
var csrfProtection = csrf({ cookie: true }); // doesn't work either
require('passport')(passport);
app.use(cookieParser("foo"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); //extended: true|false does not make any difference
app.use(session({
//foo
}));
app.use(passport.initialize());
app.use(passport.session());
require('./app/routes.js')(app, passport); //routes inside here cause a ReferenceError: csrfProtection is not defined
http.createServer(app).listen(port);
https.createServer(options, app).listen(443, function () {
//foo
});
-- routes.js --
var csrf = require('csurf'), //this needs to go in here
csrfProtection = csrf(); //this needs to go in here
module.exports = function(app, passport) {
app.route('/somepage')
.get(csrfProtection, function(req, res) {
res.render('somepage', { csrfToken: req.csrfToken()});
});
};
-- routes.js end--
For some strange reason csrfProtection remains unknown inside my page routes causing a ReferenceError (see comment inside code). What am I missing?
EDIT:
ignoreMethods
An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].
Try and set it to ['HEAD','OPTIONS']
csrfProtection = csrf(
{ cookie: true, ignoreMethods:['HEAD','OPTIONS' ] }
)
I also tried req.session.destroy() but it throws me an error saying => Error: req.flash() requires sessions.
// Logout route
router.get('/logout' , (req , res) => {
req.logOut();
// req.session.destroy();
req.flash('success_msg' , 'You are successfully logged out');
res.redirect('/users/login');
})
module.exports = router;
require part of app.js
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
const flash = require('connect-flash');
const session = require('express-session');
require('./config/passport')(passport);
const db = require('./config/database');
middleware of app.js
handlebar middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
express session middleware
app.use(
session({
secret: "my secret",
resave: true,
saveUninitialized: true
})
);
app.set('view engine', 'handlebars');
passport
app.use(passport.initialize());
app.use(passport.session());
flash middleware
app.use(flash());
I unable to run node main file in terminal
and I am using handlebar as template engine
getting this weird error
I did npm install all dependencies which is required. but still getting this error.
/home/mohsin/Desktop/mohsin/react/react-web-app/node_modules/express/lib/application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
this is error screenshot please have look https://i.imgur.com/c6zoaA6.png
My app.js file
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-sessions');
const passport = require('passport');
const mongoose = require('mongoose');
// Port env
const port = 3000;
// Route files
const index = require('./routes/index');
const user = require('./routes/user');
// Init App
const app = express();
// View Engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
// Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Start server
app.use('/', index);
app.use('/user', user);
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
There is no package named 'express-sessions'
instead use express-session
so its not returning any method. which app.use can call as method.
Here is package
I've checked the other related questions and can't pinpoint what's causing the issue (don't have a lot of experience here). I'm trying to launch this app locally basically with its default settings (other than some Twilio keys), have the dependencies installed, mongo is running, but localhost:5000 returns CANNOT GET /.
> node server.js
listening on port 5000
server.js:
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http); //real-time chat
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// configuration ===========================================
// public folder for images, css,...
app.use(express.static(__dirname + '/public'))
// config files
// database
var db = require('./config/db');
// models
var User = require('./app/models/users');
var Message = require('./app/models/messages');
//parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); //for parsing url encoded
//AUTH========================================================
app.use(cookieParser());
app.use(require('express-session')({
secret: 'white rabbit',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// passport config
var Member = require('./app/models/members');
passport.use(new LocalStrategy(Member.authenticate()));
passport.serializeUser(Member.serializeUser());
passport.deserializeUser(Member.deserializeUser());
// view engine ejs
app.set('view engine', 'ejs');
//chat namespace
var chatSocket = io.of('/chat')
//routes
require('./app/routes/routes')(app, chatSocket);
//Heroku port
app.set('port', (process.env.PORT || 5000));
//ADMIN====================================================
//create an admin account if none exists
var admin = Member.find({admin: true}, function(err, admins) {
if (err) throw err
else if(admins.length == 0){
//no admin. create default account
Member.register(new Member({username: "admin", admin: true}), "mypassword", function(err, admin){
if(err) throw err;
console.log('Defaut account created successfully!');
})
}
else{
//at least one admin exists
console.log('Admin account already exists : ');
console.log(admins)
}
});
//START ===================================================
http.listen(app.get('port'), function(){
console.log('listening on port ' + app.get('port'));
});
//SOCKET ==================================================
require('./app/controllers/socket')(chatSocket, User, Message);
You didn't set any route that points to /
Point to that route by using app.get
app.get("/", function(req, res) {
res.send("home");
});
There are available routes in /app/routes/*.js files of the repository you cloned.
How can I create session in expressjs(4.0)?
I am doing exactly same in the links
var session = require('express-session');
/* session */
app.use(session({ secret: '1s2sd25asd7asd5asd7f4f1f'}))
However it gives error?
TypeError: Cannot read property 'connect.sid' of undefined
How do I create session in expressjs? I have been trying to create session for 3 days.
In express 4, create session like this
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
You have to must use cookieParser before session
app.use(cookieParser())
app.use(session({secret: 'MySecret'}));
for further information, read connect official documentation here
Complete code :
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({secret: 'ssshhhhh'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var sess;
app.get('/',function(req,res){
sess=req.session;
//Session set when user Request our app via URL
if(sess.email)
{
/*
* This line check Session existence.
* If it existed will do some action.
*/
res.redirect('/admin');
}
else{
res.render('index.html');
}
});
app.post('/login',function(req,res){
sess=req.session;
//In this we are assigning email to sess.email variable.
//email comes from HTML page.
sess.email=req.body.email;
res.end('done');
});
app.get('/admin',function(req,res){
sess=req.session;
if(sess.email)
{
res.write('
<h1>Hello '+sess.email+'</h1>
');
res.end('Logout');
}
else
{
res.write('
<h1>Please login first.</h1>
');
res.end('Login');
}
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
}
else
{
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
Read here : http://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/