express-session closing in a minute and displaying err - javascript

After deployment of my app on hosting service i run into problem of this message displaying after 3-5 get requests:
Incomplete response received from application
after that more of those errors popped out and session reseted
code of app.js:
// native node and express
const path = require('path');
const express = require('express');
const app = express();
const session = require('express-session');
const env = require('dotenv');
env.config();
const ruteing = require('./routeing/main');
const messageRouteing = require('./routeing/messages');
const authenticationRoutering = require('./routeing/authentication');
//set extenction settings
app.set('views', path.join(__dirname, 'views'));
app.set('render engine', 'pug');
app.use(express.urlencoded({ extended: false}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
// create access routing from exported rutering
app.use('/', ruteing);
app.use('/m', messageRouteing);
app.use('/a', authenticationRoutering);
app.get('*', (req, res) => {
res.render('404.pug');
});
app.listen(3000, () => console.log('i do not even know what am i doing'))```
My hosting is mydevil

Related

repo NOT set to continours integration in github

please i need your help, i have pushed my glitch website to github and finally push to heroku for deployment. When i did deployment i have some errors, and i come to understand that my repo was not set to continuous integration. now where in github can i navigate to set the repo to continous integration, before going back to deploy from heroku, thank you.
//start server: node engine
const express = require("express");
const app = express();
const compression = require('compression')
const dbInitiation = require("./construct/dbs");
const bodyParser = require("body-parser");
const dotenv = require("dotenv").config({path: "./.env"});
const userRoute = require("./routes/user");
const passport = require("passport");
const session = require("express-session");
const cookieParser = require('cookie-parser');
const MemoryStore = require("memorystore")(session);
//set directory for views template files
app.set('views', './views');
//set view engine
app.set('view engine', 'pug');
//middleware
app.use(compression())
app.use("/public", express.static(__dirname + "/public"));;
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser(process.env.SESSION_SECRET))
app.use(express.json());
require("./passport/local")(passport);
dbInitiation();
app.use(cookieParser())
const sessionStore = new MemoryStore({
checkPeriod: 86400000
});
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
key: "express.sid",
store: sessionStore,
}));
//
app.use(passport.initialize());
app.use(passport.session());
//use routes function
userRoute(app);
app.listen(process.env.PORT, function(req, res) {
console.log("app running on port:", process.env.PORT);
});

NodeJS + Express: share session across multiple routes

I have an Express web application with some routes. The routes need to share the session when the web app interacts with users. The routes are declared in separate js files from the app.js.
In my app.js
var createError = require('http-errors');
var express = require('express');
var parseurl = require('parseurl')
var session = require('express-session')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var p_conf = require('./parse_config');
// Declare routes here
var indexRouter = require('./routes/index'); // index route
var usersRouter = require('./routes/users'); // user route
var itemRouter = require('./routes/items'); // item route
var app = express();
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')));
// set up express-session
var sessionMiddleware = session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/items', itemRouter);
// Assign an object to the session
app.use(function (req, res, next) {
req.session.test = "test";
next();
});
module.exports = app;
In my item.js for the item route:
const path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const router = express.Router();
const p_conf = require('../parse_config');
const db_item = require('../db/db_item');
/* GET route root page. */
router.get('/', function(req, res, next) {
// Get the object in the session
console.log(req.session.test);
db_item.getItems()
.then(function(result) {
if (typeof result === "object")
return res.send(result["results"]);
else
return res.send(JSON.stringify({ "Error": String(result) }));
})
.catch((err) => {
return next(err);
})
});
module.exports = router;
In the app.js the session is created and assigned with a test object when the web app is initialised. The item route is supposed to get the same session and retrieve the test object. However, req.session.test is always undefined when the route root is accessed.
How can the item and user routes access the session and share the session scoped objects across?
Try changing the order of declaring routes and session in app.js. Also, need to use sessionMiddlware (app.use) before using session.
var sessionMiddleware = session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
});
app.use(sessionMiddleware);
app.use(function (req, res, next) {
req.session.test = "test";
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/items', itemRouter);

Cannot GET with nodejs?

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

Error: Missing Helper: "iff"

For some reason, I keep getting this error every time i try to use {{#iff}
Is this not rendering my page as handlebars? Did I use the {{#iff}} statement correctly?
My console prints this out:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my handlebars(login.hbs):
<h1><span class="fa fa-sign-in"></span> Login</h1>
{{#iff message.length '>' 0}}
<div class="alert alert-danger">{{message}}</div>
{{/iff}}
This is my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
const hbs = require('hbs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'hbs'); // set up hbs for templating
// required for passport
app.use(session({
secret: 'ilovescotchscotchyscotchscotch', // session secret
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/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);
In routes.js:
app.get('/login', function(req, res) {
res.render('login.hbs', { message: req.flash('loginMessage') });
});

Error: Cannot find module 'html' , Can't serve static files

I don't know what I touched but suddenly it stopped serving my static files.
I have the following architecture:
App
Routes
Models
public
views
css
js
server.js
The Error:
Error: Cannot find module 'html'
at Function.Module._resolveFilename (module.js:325:15)
...
at /Users/.../vintageAddiction/app/routes/indexRoutes.js:12:11
indexRoutes.js:
var express = require('express');
var passport = require('passport');
var indexRouter = express.Router();
indexRouter.route('/').get( function(req, res) {
res.render('index.html'); // load the index.ejs file
});
module.exports = indexRouter;
SERVER.JS:
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./app/config/configDB.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./app/config/passport')(passport); // pass passport for configuration
// routes ======================================================================
var routes = require('./app/routes/indexRoutes.js'); // load our routes and pass in our app and fully configured passport
var adminRoutes = require('./app/routes/adminRoutes.js');
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'vintageisthelaw' })); // 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
app.use('/', routes);
app.use('/admin', adminRoutes);
// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public/'));
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jade');
// launch ======================================================================
app.listen(port);
console.log('The magic happens on :\n\n http://localhost:'+ port+'\n\n');
link to server.js
I've seen something similar to :
app.use(express.static(__dirname + '/public/views/'));
But I don't really understand why is not working
Hope you can help me guys !
In express.js order of middleware declaration is very important. You must define express.static middleware earlier than any of the routes:
SERVER.JS:
.. require
// logger must be defined first if you want log all the requests
app.use(morgan('dev'));
// after that you should define express.static middleware
app.use(express.static(__dirname + '/public/'));
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jade');
// cookie and body parser must be defined before passport and session middleware
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'vintageisthelaw' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// your routes must be defined in the end
app.use('/', routes);
app.use('/admin', adminRoutes);
app.listen(port);
console.log('The magic happens on :\n\n http://localhost:'+ port+'\n\n');

Categories