I am new in node and express and i am making logapp when i run node app.js it show an error app.use() requires a middleware function i install all the npm which was required to run the project is there any way to solve this problem i really cant understand what am i doing wrong. any help thanks in advance.this is my app.js code
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validators');
var flash = require('connect-flash');
var session = require('express-sessions');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view', 'handlebars');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
saveUninitialized:true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(flash());
app.use(function(req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
})
app.use('/', routes);
app.use('/users', users);
app.set('port', (process.env.PORT || 3000 ));
app.listen(app.get('port'), function(){
console.log('Server started on Port ' + app.get('port'));
})
I think you are using wrong npm module. Instead of
var expressValidator = require('express-validators');
use
var expressValidator = require('express-validator');
Related
After inserting ssl in my application nodejs the passportjs used for authentication layer informs that the user is not authenticated in the application after an AJAX POST is performed and the page undergoes a window.location.replace().
I have already looked at the documentation and found no reference to the problem, localhost using hpp I do not have this problem.
Would anyone help?
app.js
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require('path');
var fileUpload = require('express-fileupload');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync(path.join("key.pem")),
cert: fs.readFileSync(path.join("cert.pem"))
};
var app = express();
var expressValidator = require('express-validator');
var passport = require('passport');
var flash = require('connect-flash');
// - Cria rotas
var routes = require('./routes/index');
var usuarios = require('./routes/usuario');
var motorista = require('./routes/motorista');
var login = require('./routes/login');
var aluno = require('./routes/aluno');
var contrato = require('./routes/contrato');
var boleto = require('./routes/boleto');
var pessoa = require('./routes/pessoa');
require('./security/autenticacao')(passport);
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'reis&turlwaysrunning',
resave: true,
saveUninitialized: true
} ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
res.locals.login = req.user;
next();
});
app.use(fileUpload());
// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);
https.createServer(httpsOptions, app).listen(8080);
app.set('port', process.env.PORT || 21108);
app.listen(app.get('port'));
function logErrors (err, req, res, next) {
console.error('Troxa: ' + err.stack)
next(err)
}
module.exports = app;
I am new to Node (frameworks in general), and I have some problems that I cannot find answers to after searching for days.
When I click on a specific client, I now get redirected to 'create-survey' which is correct. But after that I want the url to be something like '/create-survey/companyx' and get the data with me from that specific client that I clicked on in the new view '/create-survey/companyx'.
index.js:
router.get('/create-survey/:company', ensureAuthenticated, function(req, res) {
Client.find({}, {}, function (err, docs){
res.render('create-survey/:company', {"client" : docs});
})
});
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
// Routes
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect to Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use(express.static('public'));
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
and the last, create-survey.handlebars
<h2 class="page-header">Create a survey for {{client.company}}</h2>
<tr>
<strong>Company</strong>
<td><p>{{client.company}}</p></td>
<strong>Contact person</strong>
<td><p>{{client.contact}}</p></td>
<strong>Email adress</strong>
<td><p>{{client.email}}</p></td>
</div>
As I said, I'm a beginner that still is trying to learn, so come with all kind of feedback and help and I'll be happy!
I have a simple nodejs app with some users. I want to load a specific user profile using a URL localhost/users/(username) but I'm getting this error when I try to load the URL:
Cannot GET /users/test
Here's my user.js routes file for the user page:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.send(req.params);
res.render('user');
});
module.exports = router;
I have a user.handlebars file in my views folder so it should load the file. What am I missing in my routes file? Any help would be greatly appreciated. Thanks!!
EDIT: app.js:
console.log('Starting app.js');
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/users/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Render function renders a view and sends the rendered HTML string to the client.Take a look at documentation.
But what you are trying to archive is to send data first and then render and send again. So, just delete the line with send.
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.render('user');
});
And, please, edit your question by adding your code with middleware and add your error.
Update
Take a look at the way how you define your routes for users.
You have to remove /users from defining route in users.js file
Ive been recently learning how to use node.js to create a backend login system with passport. Im running it locally with a mongoDB. The url I use to access it is http://localhost:3000. Now when I go to that url instead of displaying my index.handlebars page it routes me to http://localhost:3000/users/login. Im wondering why this is? Ill provide a few files let me know if there is anything else you may need.
Not sure what else you would need, but I have looked through my code hundreds of times and cant find out why. My routes seem fine, my static folder seems fine. Im just lost. Any help would be appreciated.
My directory looks like this,
loginapp-master
-models
-users.js
-node_modules
-public
-css
-fonts
-js
-routes
-index.js
-users.js
-views
-layouts
-layout.handlebars
-index.handlebars
-login.handlebars
-register.handlebars
.gitignore
app.js
package-lock.json
package.json
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
a question which was often discussed(error message: Router.use() requires middleware function but got a Object) , but the answers in the other feeds does'nt work. e.g.
app.use(app.router);
routes.initialize(app);
This code brings the message:
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x
migration guide for details on how to update your app.');
^
Error: 'app.router' is deprecated!
Please see the 3.x to 4.x migration guide for details on how to update your app.
I hope there will be a better idea.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/dbname');
//var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//Init App
var app = express();
//View Engine
app.set('views',path.join(__dirname,'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine','handlebars');
//BodyParser Middleware
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedParser);
app.use(cookieParser());
//Set Static Folder
app.use(express.static(path.join(__dirname,'public')));
//Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passprt init
app.use(passport.initialize());
app.use(passport.session());
//Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//Connect Flash
app.use(flash());
//Global Vars
app.use(function(req,res, next) {
res.locals.success_msg = req.flash('succes_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
//Set Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
// Set Port
app.set('port',(process.env.PORT || 3000));
//Start Server
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});