Unable to use express sessions in heroku nodejs app - node.js

In my app.js I have:
var express = require('express')
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var flash = require('connect-flash');
....
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('3mKay'));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.session({ secret: 'thisISmyS3cR3t'}));
This crashes with the following message in Heroku.
Error: Most middleware (like session) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (/app/node_modules/express/lib/express.js:89:13)
at Object.<anonymous> (/app/app.js:25:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
I ran so it does exist in the package.json file as well:
npm install express-sessions --save
"dependencies": {
....
"express": "~4.8.6",
"express-session": "^1.8.1",
"passport": "^0.2.1",
"passport-local": "^1.0.0",
....
It works fine when I comment out the
app.use(express.session({ secret: 'thisISmyS3cR3t'}));
And I've also tried variations of the above but it gives the same error message. Any ideas what may be causing this to happen? Something I might have overlooked...

Once you install it, you have to actually use it in your code:
var express = require('express');
var session = require('express-session');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var flash = require('connect-flash');
....
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('3mKay'));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(session({ secret: 'thisISmyS3cR3t'}));

Related

Cannot access 'pool' before initialization

I am currently experimenting with passing queries from postgres database and loading it into a page. I have setup a test page with the following code below :
const sql_query = require('../sql');
var express = require('express');
var router = express.Router();
const { Pool } = require('pg')
const pool = new pool ({
connectionString: process.env.DATABASE_URL
});
pool.query('SELECT * FROM rides', [1], (err, res) => {
if (err) {
throw err
}
console.log('user:', res.rows[0])
})
module.exports = router;
However, when i run npm test, the stack trace is as follows:
/Users/lawjiahua/Desktop/CS2102_proj/App/routes/testPage.js:6
const pool = new pool ({
^
ReferenceError: Cannot access 'pool' before initialization
at Object.<anonymous> (/Users/lawjiahua/Desktop/CS2102_proj/App/routes/testPage.js:6:14)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Module.require (internal/modules/cjs/loader.js:838:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/lawjiahua/Desktop/CS2102_proj/App/app.js:25:22)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
Here is my part of my main app file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
const pg = require('pg');
var app = express();
require('dotenv').config();
/* PAGES FOR THE PROJECT */
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var driverRouter = require('./routes/driver');
var awaitingApprovalRouter = require('./routes/awaitingApproval');
var registerDriverRouter = require('./routes/registerDriver');
var ridesRouter = require('./routes/rides');
var homepageRouter = require('./routes/homepage');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var testPageRouter = require('./routes/testPage');
// 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')));
/* FOR PROJECT */
app.use('/', indexRouter);
app.use('/driver', driverRouter);
app.use('/awaitingApproval', awaitingApprovalRouter);
app.use('/registerDriver', registerDriverRouter);
app.use('/rides', ridesRouter);
app.use('/homepage', homepageRouter);
app.use('/testpage', testPageRouter);
module.exports = app;
What does the error refer to? Do i have to initialise pool in the app.js page in order to use it in routes?
if you are creating an object with your module Pool, it should be upper case.
const { Pool } = require('pg')
const pool = new Pool ({
connectionString: process.env.DATABASE_URL
});
pool.query('SELECT * FROM rides', [1], (err, res) => {
if (err) {
throw err
}
console.log('user:', res.rows[0])
})

Mongoose is undefined error

First time i have tried out to create a simple mean application.
I have followed the steps as per the below link
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application#starting-our-node-application-packagejson
Finally i am getting the errors as
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\Users\Myname\Desktop\Mean sample\server.js:19:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server.js
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
// (uncomment after you enter in your own credentials in config/db.js)
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
// expose app
exports = module.exports = app;
How to fix it?
Can anyone please explain the steps to clear this issue
install mongoose
npm i mongoose --save
then import in your server.js file
var express = require('express');
var mongoose = require('mongoose') // import it
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

Express routes doesn't work

I'm doing a web page with the express generator, I have three pages in jade, but when I want to go from one to another it shows me this mistake:
Error: Not Found
at app.use.res.render.message (F:\NodeJSPortable\Data\letstalksaku\app.js:39:13)
at Layer.handle [as handle_request] (F:\NodeJSPortable\Data\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:312:13)
at F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:280:7
at Function.process_params (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:330:12)
at next (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:271:10)
at SendStream.error (F:\NodeJSPortable\Data\node_modules\express\node_modules\serve-static\index.js:120:7)
at SendStream.emit (events.js:95:17)
at SendStream.error (F:\NodeJSPortable\Data\node_modules\express\node_modules\send\index.js:245:17)
at SendStream.onStatError (F:\NodeJSPortable\Data\node_modules\express\node_modules\send\index.js:356:12)
This is the code from app.js:
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 fs = require('fs');
var https = require('https'),
http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
var index2 = require('./routes/index2');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
require('./routes')(app);
module.exports = app;
https.createServer({key: privateKey, cert: certificate}, app).listen(8000);
http.createServer(app).listen(8001);
console.log('running on https://localhost:8000 and http://localhost:8001');
My jade files just have this code
doctype html
html
head
body
a#Boton1(href='/index2') Crea tu sala
I just can't find the mistake, would you please help me

express - app `index.jade` not properly supplied by the `exports` function

I am trying to make a app, in the app directory this is my app.js file. in the app.js I am requiring the router folder and exporting the Routes. But I am not able to render the index.jade using the Router instead i am getting error:
D:\Projects\socialApp\node_modules\express\lib\router\index.js:423
throw new TypeError(msg);
^
TypeError: Router.use() requires callback function but got a [object Undefined]
at D:\Projects\socialApp\node_modules\express\lib\router\index.js:423:13
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\router\index
.js:419:13)
at D:\Projects\socialApp\node_modules\express\lib\application.js:178:21
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\application.
js:175:7)
at Object.<anonymous> (D:\Projects\socialApp\app.js:22:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
D:\Projects\socialApp>
here is my app.js:
var express = require("express"),
passport = require("passport"),
passportLocal = require("passport-local"),
bodyParser = require("body-parser"),
cookieParser = require("cookie-parser"),
expressSession = require("express-session"),
jade = require("jade"),
mongoose = require("mongoose"),
routes = require('./routes'),
port = process.env.PORT || 3000,
app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
var routes = require('./routes/index')(passport); //i am calling here
app.use('/', routes); // not getting index.jade on screen.
app.listen(port, function(){
console.log('Port Listing to ' + port + ":" + __dirname);
});
here is what in the router folder and in the index.js:
var express = require('express'),
router = express.Router();
module.exports = function(passport){
router.get('/', function(req,res){
res.render('index'); //i am not getting index.jade from view folder getting error
});
}
any one figure-out the issue please?
You need to return router; at the end of your module.exports function.

nodejs/express - cannot load routes using passport

I am trying to use passport to add user sessions on my webapp. I have configure my main js file as follow:
/**
* Module dependencies.
*/
var express = require('express');
var user = require('./server/routes/user');
var routes = require('./server/routes/index');
var http = require('http');
var path = require('path');
var app = express();
var passport = require('passport');
var flash = require('connect-flash');
require('./server/config/passport')(passport); // pass passport for configuration
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.configure(function(){
// required for passport
app.use(express.session({ secret: 'ilovesefounders' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
})
// routes ======================================================================
require('./server/routes/index')(app, passport); // load our routes and pass in our app and fully configured passport
routes.mount(app);
However when i try to launch it I get the following error:
require('./server/routes/index')(app, passport); // load our routes and pass i
^
TypeError: object is not a function
at Object.<anonymous> (/Path/app.js:38:33)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
What's going wrong here?
I don't know how your index.js looks like but you probably did not export your function module.
Check if index.js looks something like this:
module.exports = function(app, passport) {
/* code */
};
And you don't need to require "./server/routes/index" again.

Resources