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
Related
const express = require('express');
const cookieParser = require('cookie-parser');
const port = 8000;
const app = express();
const expressLayout = require('express-ejs-layouts');
const db = require('./config/mongoose')
// used for session cookie
const session = require('express-session')
const passport = require('passport')
const passportLocal = require('./config/passport-local-strategy')
app.use(express.urlencoded())
app.use(cookieParser());
// where to look static files like css,js
app.use(express.static('./assets'))
// this line must be above the routes line (line no. 11 in this case) because in the routes all the views are going to be render and before that we have to tell to the browser the layout
app.use(expressLayout)
// extract style and scripts from sub pages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
// set up the view engine
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(session({
name: 'iFacebook',
// TODO change the secret before deployment in production mode
secret: 'Coder',
saveUninitialized: false,
resave: false,
cookie: {
maxAge : (1000*60*100)
}
}))
app.use(passport.initialize());
app.use(passport.session())
// use express router
// require('./routes/index) is similar to require('./routes) in this case, it by default fetch routes
app.use('/', require('./routes/index'))
app.listen(port, (err) => {
if (err) {
console.log(`Error in running the server : ${err}`);
}
console.log(`Server is listening at ${port}`);
})
I am using passport and passport-local strategy and this error comes and even i did not know from which file this error comes. I am sharing the index.js file code which is the server file. This is the first time i am using this even on the documentation i did not found anything
Well, as the title suggests, I broke everything using socket.io. Mainly because the way it calls express breaks everything else using express.
Here is my old way of doing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Which works wonders! It works, however adding socket.io like so:
/*jshint esversion: 6*/
const app = require('express')();
const http = require('http').Server(app);
const socket = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
// app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Breaks everything using express.* because it is saying express is not defined. So my static path gets broken and of course the app crashes.I tried several solutions, but to no avail.
Oops forgot to add the error:
app.use(express.static(path.join(__dirname, 'static')));
^
ReferenceError: express is not defined
Try this. The idea is that you need to import express. Socket.io can be required once the rest is defined.
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// Init socket
const socket = require('socket.io').listen(server);
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
I have only realised that this has been happening.
My stack:
NodeJS
Express
PassportJS
Angular
MongoDB with Mongoose
When I log into my website, I see that the collection sessions is created, with one record (as one would expect). Then, I navigate around the website and noticed that my sessions have goes to 13 records. Then, I navigate some more and I see that it has gone over 27.
What in the world is going on? Am I doing something that is causing this?
My main app.js file is below:
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(session({secret:config.sessionSecret, saveUninitialized:true, resave:true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});
Each one of my sessions look like the below (if it helps in any way):
{
"_id": "cSqLjOGJlYBvNLYJ8v6zXqtqzuIcGwbx",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"}}",
"expires": "2017-10-10 22:46:09",
"lastModified": "2017-09-26 22:46:09"
}
Try this
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(passport.initialize());
app.use(passport.session());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});
I'm building a home automation system in NodeJS and I want to fire some commands on my raspberry pi using the Shell_exec function in Express. How can I do this with an onclick event in JADE?
This is my app.js in Express:
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 shell_exec = require('shell_exec').shell_exec;
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/homeapp');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var index = 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', 'jade');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public/images', 'favicon-32x32.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
var User = require('./models/User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
module.exports = app;
And this is my index.js with the routing:
var express = require('express');
var router = express.Router();
var auth = require('../controller/AuthController.js');
router.get('/', auth.home);
router.get('/login', auth.login);
router.post('/login', auth.doLogin);
router.get('/logout', auth.logout);
module.exports = router;
And this is the jade file where I want the onclick event to exucute the commands:
div.btn(onclick="shell_exec");
You can't call any Node.js command from Jade view. Jade view is parsed in client's browser and any javascript commands you write in that file will be executed in browser.
In the view you should add code which will create AJAX request to the node.js server and in the node.js app create route which will handle the request and execute the command (shell_exec).
In my understanding, the way to serve views is to do the following:
app.set('view engine', 'ejs'); // or jade or whatever
app.set('views', __dirname + '/views'); // specify where to find the view files e.g. index.ejs
app.get("/", function(req, res) { res.render('index') });
However, when I check the code here https://github.com/jedireza/drywall/ , which is a boilerplate for node user management, I don't see any routes defined in app.js. But it works fine and if I type the url /signup in browser it will render signup.jade.
Which part, or which middleware is doing the magic of routing?
app.js content:
'use strict';
//dependencies
var config = require('./config'),
express = require('express'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
csrf = require('csurf');
//create express app
var app = express();
//keep reference to config
app.config = config;
//setup the web server
app.server = http.createServer(app);
//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
//and... we have a data store
});
//config data models
require('./models')(app, mongoose);
//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.cryptoKey,
store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf({ cookie: { signed: true } }));
helmet(app);
//response locals
app.use(function(req, res, next) {
res.cookie('_csrfToken', req.csrfToken());
res.locals.user = {};
res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
res.locals.user.username = req.user && req.user.username;
next();
});
//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';
//setup passport
require('./passport')(app, passport);
//setup routes
require('./routes')(app, passport);
//custom (friendly) error handler
app.use(require('./views/http/index').http500);
//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');
//listen up
app.server.listen(app.config.port, function(){
//and... we're live
});
The routes are being added here:
//setup routes
require('./routes')(app, passport);