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);
});
Related
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
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'));
});
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');
I am trying to setup Redis for a session store, but is not working at. I'm using passport.js and express-flash, and if I try run the current Redis setup, it won't work:
var session = require('express-session');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var redis = require("redis").createClient();
var RedisStore = require("connect-redis")(session);
var load = require('express-load');
var flash = require('express-flash');
var path = require('path');
var logger = require('morgan');
var i18n = require('i18n-2');
var passport = require('passport');
var mongoose = require('mongoose');
If I use this session setup:
app.use(session({
secret: 'keyboard cat'
}));
This will show an error saying that is not safe for use in production, however the passport.js and the express-flash will work.
Moving on to Redis:
app.use(session({
store: new RedisStore({
host: 54.94.171.197,
port: 3000,
client: redis
}),
secret: 'keyboard cat'
}));
Should I put the static IP in the host and the 3000 in the port? I am very confused with the proper values that I need pass to the new instance.
This is my middleware:
app.use(favicon(__dirname + '/public/images/icons/fav.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(flash());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
store: new RedisStore({
host: global.config.site.host,
port: 6379,
client: redis
}),
secret: 'keyboard cat'
}));
// Productions Middlewares
if (process.env.NODE_ENV === 'production') {
app.use(passport.initialize());
app.use(passport.session());
app.use('/admin', middleware.ensureAuthenticated);
app.use(middleware.ensureHttps);
}
It’s bad practice to have your application’s configuration inside the code.
Use something like nconf to have your configuration out of the code.
For example you could use a config.json file:
{
"sessionSecret": "cat something",
"redis": {
"host": "localhost",
"port": 6379
}
}
Configure nconf to look for the configuration file
var nconf = require('nconf');
nconf.file({ file: '/path/to/config.json' })
Then use the configuration in your session middleware
app.use(session({
store: new RedisStore({
host: nconf.get('redis:host'),
port: nconf.get('redis:port'),
client: redis
}),
secret: nconf.get('sessionSecret')
}));