Hi I'm trying doing a login page, after clicking on submit I'm getting this error with express-validator version 5.3.1
req.checkBody is not a function
TypeError: req.checkBody is not a function
at Strategy._verify (C:\Users\aless\Desktop\js_cart-master\config\passport.js:67:7)
at Strategy.authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:369:16)
at authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:370:7)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:275:10)
at C:\Users\aless\Desktop\js_cart-master\routes\user.js:39:3
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:317:13)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
In my app.js I have required express-validator with const validator = require('express-validator');//#5.3.1
and used it with app.use(validator());
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const passport =require('passport');
const flash = require('connect-flash');
const bcrypt = require('bcrypt');
const validator = require('express-validator');//#5.3.1
const session = require('express-session');
const MongoStore = require('connect-mongo');
const env = require('dotenv').config()
const app = express();
mongoose.connect(process.env.URI,{ useNewUrlParser: true });
require('./config/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
secret: "key per i cookie",
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: process.env.URI,
autoRemove: 'disabled'
}),
cookie: { maxAge:30000,secure:false }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//verify if authenticated
app.use((req, res, next)=>{
res.locals.login =req.isAuthenticated();
//access sessions through templates
res.locals.session = req.session;
next();
});
//routes
app.use('/', require('./routes/index'));
app.use('/user', require('./routes/user'));
// 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;
Using this express-validator version I got this error when submit, using last express-validator version I get same error in console.
Why I'm getting this error??
The reason is the way you are requiring it.
const { body, validationResult } = require('express-validator');
In your code you can make these changes and try:
const { validationResult } = require('express-validator');//#5.3.1
.
.
.
app.use(validationResult());
Note: check this link for more information.
Related
I used express-generator and the following are 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 cors = require('cors');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
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;
And when access to http://localhost:5000/api/ got Error:
Not Found
404
NotFoundError: Not Found
at D:\_projects\booking-system\api\app.js:28:8
at Layer.handle [as handle_request] (D:\_projects\booking-system\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\_projects\booking-system\api\node_modules\express\lib\router\index.js:317:13)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:335:12)
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:275:10)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:635:15
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:260:14)
at Function.handle (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:174:3)
at router (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:47:12)
Following is routes/index:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Thank you very much for your helps !
The issue is that you define a GET / route in your routes/index.js file and then register it as app.use('/', indexRouter) in your app.js.
So you either change your routes/index.js file to it looks like this:
var express = require('express');
var router = express.Router();
// Note the /api
router.get('/api', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Or you keep routes/index as it is but your change the way your register it in your main.js to this:
// ...
// Note the /api
app.use('/api', indexRouter);
app.use('/users', usersRouter);
// ...
I'm setting up a new server with node js and the framework express (Version 4.16). I want to route my Rest-Endpoints. In my route.js-file i want to call a function from app.js(my Server), but getting a Typeerror where the function, that i want to call from another file, is not a function.
Error:
TypeError: callFunction.getDataFromDb is not a function
at C:\Users\---\WebstormProjects\pwa_node_server\routes\recipes.js:7:18
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:47:12)
My server:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var axios = require('axios');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipesRouter = require('./routes/recipes');
var cors = require('cors');
var app = express();
// 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(cors({credentials: true, origin: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/recipes', recipesRouter);
// app.use('/poste-dein-rezept', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log("catch404");
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');
});
var getDataFromDb = function (res) { // This function to call in another file
};
module.export = {
getDataFromDb
};
module.exports = app;
My route-file:
var express = require('express');
========
var router = express.Router();
var callFunction = require('../app');
router.get('/', function(req, res, next) {
console.log('Recipes-Endpoint received Request');
callFunction.getDataFromDb(res);
});
module.exports = router;
I just want to call a function from another file.
You're using module.export. The Correct property name is module.exports, which you are also using.
One way to solve this is:
app.getDataFromDb = getDataFromDb;
module.exports = app;
Error: Failed to lookup view "error" in views directory "/var/www/html/mean/mean-secure1/views"
at Function.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/application.js:581:17)
at ServerResponse.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/response.js:1008:7)
at /var/www/html/mean/mean-secure1/app.js:50:7
at Layer.handle_error (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:315:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at /var/www/html/mean/mean-secure1/app.js:39:3
at Layer.handle [as handle_request] (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:317:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/var/www/html/mean/mean-secure1/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:182:13)
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database');
var api = require('./routes/api');
var app = express();
//app.set('view engine', 'pug');
mongoose.Promise = require('bluebird');
mongoose.connect(config.database, { promiseLibrary: require('bluebird') })
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
app.use(passport.initialize());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/books', express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
//app.use(express.static(path.join(_dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// 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;
If you want to use ejs templating as your view engine then you can use below code to set the view engine for your node application
const ejs=require("ejs");
app.set('view engine','ejs');
I was trying to write some test which will emulate the post, but I have realised that nothing is posting. After further debugging, I realised that req.body is always undefined. Question is where did I make a mistake and how do I fix it. I seems that the problem is somewhere in the app.js file with order how the middleware loads but I can not figure it out where.
app.js
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const fs = require('fs');
const session = require('express-session');
const redis = require('redis');
const mongoose = require('mongoose');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _UTILS = require('./application/_UTILS');
const db = JSON.parse(fs.readFileSync('/srv/webkb_mean/config/configFiles/database.json', 'utf8'));
mongoose.connect('mongodb://' + db['mongodb']['url'] + '/webKB-main');
mongoose.Promise = global.Promise;
app.use(session({
secret: _UTILS.getHashedValue(),
// create new redis store.
store: new redisStore({
host: 'localhost',
port: 6379,
client: client,
ttl: 36000
}),
saveUninitialized: false,
resave: false
}));
require('./config/router')(app);
// 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(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
app.engine('html', require('ejs').renderFile)
// 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;
Your adding your bodyParser middleware to your server after you’ve added your routes. This is because express executes middleware(which includes routers since they are also middleware) in the order which they were added via .use().
Just move your router registration line:
require('./config/router')(app);
After your last middleware and before your 404 NOT FOUND handler.
app.engine('html', require('ejs').renderFile)
require('./config/router')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
I'm trying to add connect-mongo in order to save sessions when nodeJS restarts.
Per the documentation I added:
MongoStore = require('connect-mongo')(session),
and in my require('express-session') I added
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
and commented out app.use(passport.session());
I'm getting an error: ReferenceError: session is not defined which is pointed to MongoStore = require('connect-mongo')(session),
I've added my app.js file for reference. How can I fix this?
'use strict';
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(session),
passport = require('passport'),
flash = require('connect-flash'),
LocalStrategy = require('passport-local'),
methodOverride = require('method-override'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
User = require('./models/user'),
faker = require('faker'),
path = require('path');
const indexRoute = require('./routes/index'),
usersRoute = require('./routes/users'),
giftsRoute = require('./routes/gifts.js'),
searchRoute = require('./routes/search');
const mongooseDB = 'mongodb://localhost/giftcashing';
mongoose.connect(mongooseDB);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(methodOverride("_method"));
app.use(flash());
app.use(require('express-session')({
secret: 'anything',
resave: false,
saveUninitialized: false,
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
}));
// PASSPORT CONFIGURATION
app.use(passport.initialize());
// app.use(passport.session());
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.use('/', indexRoute);
app.use('/users', usersRoute);
app.use('/gifts', giftsRoute);
app.use('/search', searchRoute);
module.exports = app;
The variable session is not initialized when you are calling
MongoStore = require('connect-mongo')(session).
Add session = require('express-session') before initializing MongoStore.