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');
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
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'));
});
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') });
});
I am building an api that will interface with the MongoDB database and have mounted it as a subapplication. I have defined a session variable in my server controller.
However, any time that the server files need to talk to the api files the session variables are never passed off.
Heres the app.js file
//app.js file
'use strict';
process.env.NODE_ENV = 'development';
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
app.use(helmet());
var port = process.env.PORT || 3000;
mongoose.connect("mongodb://localhost:27017/striv4");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use(flash());
// make user ID available in templates
app.use(function (req, res, next) {
res.locals.currentUser = {
username:req.session.username,
id: req.session.userId
};
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secreter'));
app.use(logger('dev'));
var api = require('./app_api/routes/index');
var serverRoutes = require('./server/routes/index');
//static file middleware
app.use(express.static(__dirname + '/public'));
app.set('views',__dirname +'/server/views');
app.set('view engine','pug');
app.use('/',serverRoutes);
app.use('/api',api);
//custom error handler
app.use(function(error, req, res, next) {
res.status(error.status || 500);
res.send('Error: '+error.message);
});
app.listen(port);
console.log('Listening on port: '+port);
You've got the whole program listed so there is more than one way for this to have gone wrong. Here are my suggestions to fix this:
Check the version of express-session you've installed. (Just run npm ls in the terminal and in your root Node app folder where you're package.json file is). If it's equal to or greater than v1.5.0, you don't need the cookie-parser for sessions anymore. Comment out the app.use line for the cookie parser and see if this works.
If you still need cookie parser for some other reason, you should use the same secret for sessions and the cookie parser. In your code, you've set two different values for secret.
I've seen that the other big failure for sessions occurs if the session store is not correctly connected to your Node app. Cross-check that the database is available and working. In my experience, Express sessions will fail silently if it can't get to the DB.
Hope this helps.
I am new to NodeJS and ExpressJS development (a week old or so). I am trying to create a web application in NodeJS using ExpressJS framework. One of the things I am trying to do is build a registration form for my app. I have installed body-parser middleware using the npm to read form data.
I am using HoganJS as my template framework. I have a page in my views folder named register.hjs. This page has a form
<form method="post">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit">
</form>
I am struggling with these two issues:
How to read form values in the .js
How to redirect a user to a different page once form is submitted.
This is what I am trying to do (it might be incorrect though).
In my app.js
//get
app.get('/register', routes.register);
//post
app.post('/welcome', routes.welcome);
In my index.js
/* GET about page.*/
exports.register = function(req, res) {
res.render('register');
};
/*POST registered user*/
exports.welcome = function(req, res) {
// pull the form variables off the request body
var name = req.body.name;
var age = req.body.age;
//just to make sure the information was read
console.log(name);
console.log(age);
res.render('welcome');
};
I am pretty sure I am missing something cause when I run my server it gives an error saying :
Error: Route.get() requires callback functions but got a [object Undefined]
What am I doing wrong? Is there any elegant way to read form data and redirect users to different pages?
Thanks.
--------------------------- Update ----------------------------
Here is the rest of the app.js Code
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');
//routes to the pages
var routes = require('./routes/index');
var users = require('./routes/users');
var register = require('./routes/register');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views')); //app.set('the name of your view folder', )
app.set('view engine', 'hjs');
//get
app.get('/register', routes.register);
//post
app.post('/welcome', routes.welcome);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
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')));
app.use('/', routes);
app.use('/users', users);
app.use('/register', register);
//error handlers
//error handlers
module.exports = app;
For Simple understanding how express works for form understand this code :
After understanding this code , use router and other body parser configuration---
var express = require('express');
/*
* body-parser is a piece of express middleware that
* reads a form's input and stores it as a javascript
* object accessible through `req.body`
*
* 'body-parser' must be installed (via `npm install --save body-parser`)
* For more info see: https://github.com/expressjs/body-parser
*/
var bodyParser = require('body-parser');
// create our app
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());
// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
// The form's action is '/' and its method is 'POST',
// so the `app.post('/', ...` route will receive the
// result of our form
var html = '<form action="/" method="post">' +
'Enter your name:' +
'<input type="text" name="userName" placeholder="..." />' +
'<br>' +
'<button type="submit">Submit</button>' +
'</form>';
res.send(html);
});
// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
var userName = req.body.userName;
var html = 'Hello: ' + userName + '.<br>' +
'Try again.';
res.send(html);
});
app.listen(80);
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 routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
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')));
app.use('/', routes);
module.exports = app;
index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/register', function(req, res) {
res.render('register');
});
router.post('/welcome', function(req, res) {
console.log(req.body.name);
console.log(req.body.age);
});
module.exports = router;