Iam getting following error if I try to open the localhost:3000 or localhost:3000/login. Can someone help me what is the problem? It is very strange. Many thanks
My Code
var express = require('express');
var crypto = require('crypto');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var path = require ('path');
var port = process.env.PORT || 3000;
var MongoClient = require('mongodb').MongoClient,
ObjectID = require('mongodb').ObjectID,
url = require('url');
var db;
//var mongo;
//var collection;
//dataExt = require('./routes/serverExtend');
// setup middleware
var app = express();
app.use(bodyParser());
app.use(flash());
app.use(cookieParser('secret'));
app.use(session({cookie: { secret: 'keyboard cat', maxAge: 60000 }}));
app.use(express.static(__dirname + 'public')); //setup static public directory
app.set('views', __dirname + 'testapp/views'); //optional since express defaults to CWD/views
app.set('view engine', 'ejs');
// Start server
app.listen(port);
console.log('App started on port ' + port);
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
if(err) throw err;
db = database;
});
app.get('/', function(req, res) {
res.render('index.ejs', { message: req.flash('signupMessage')}); // load the index.ejs file
app.get('/login', function(req, res) {
res.render('login.ejs');
});
Here is my package.json
{
"name": "NodejsStarterApp",
"version": "0.0.1",
"description": "A sample nodejs"
"dependencies": {
"express" : "~4.0.0",
"ejs" : "*",
"mongodb":"*",
"connect-flash" : "~0.1.1",
"morgan": "~1.0.0",
"body-parser": "*",
"cookie-parser": "~1.0.0",
"express-session": "~1.0.0"
},
"engines": {
"node": "0.10.26"
},
"repository": {}
}
Here is the problem.
change this line
app.set('views', __dirname + 'testapp/views');
to
app.set('views', __dirname + 'views');
Because when you say just __dirname + 'views' it looks in {appName}/views/fileToRender. But because you are saying __dirname + 'testapp/views' it will search {appName}/testapp/views/fileToRender.
Related
All my projects were working fine before but all of sudden the content of the body is not being saved as if the body is not being parsed or something. Just to check I created this simple project of book directory but no luck.
Any help would be appreciated.
Thank you
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var config = require('./config');
// import bodyParser from "body-parser";//for typscript code only, use require for js
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bookRouter = require('./routes/books_routes');
const url = config.mongoURL;
const connect = mongoose.connect(url);
connect.then((DB)=>{
console.log("Connected With the MongoDB Server");
},(err)=>{next(err)})
.catch((err)=>next(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({
extended: true
})); //Parse URL-encoded bodies
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/books',bookRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Route File
const express = require('express');
const mongoose =require('mongoose');
const Books = require('../models/books');
const bookrouter = express.Router();
// bookrouter.use(bodyparser.json());
bookrouter.use(express.json());
bookrouter.use(express.urlencoded({
extended: true
})); //Parse URL-encoded bodies
bookrouter.route('/')
.get((req,res,next)=>{
Books.find({})
.then((books)=>{
res.statusCode = 200;
res.setHeader('content-Type','application/json');
res.json(books);
},(err)=>{next(err)})
.catch((err)=>next(err))
})
.post((req,res,next)=>{
var book = new Books({
book_name: req.body.book_name,
book_author: req.body.book_author,
book_description: req.body.book_description
})
book.save()
.then((book)=>{
Books.findById(book._id)
.then((book)=>{
res.statusCode = 200;
res.setHeader('content-type','application/json');
res.json(book);
},(err)=>next(err))
})
})
.put((req,res,next)=>{
res.send("PUT request is not supported at this API");
})
.delete((req,res,next)=>{
Books.remove({})
.then((resp)=>{
res.statusCode=200;
res.setHeader('content-type','application/json');
res.send(resp);
})
})
module.exports = bookrouter;
Model file
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportlocalmongoose = require('passport-local-mongoose');
var Books = new Schema({
book_name :{
type:String
},
book_author:{
type:String
},
book_description:{
type:String
}
},{
timestamps:true
})
Books.plugin(passportlocalmongoose);
module.exports = mongoose.model('Book',Books);
package.json
{
"name": "books-directory",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongodb": "^3.0.10",
"mongoose": "^5.1.7",
"mongoose-currency": "^0.2.0",
"morgan": "~1.9.1",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^5.0.1"
}
}
I created a express app and having some big issues:
My routing is horrendous and can't get my 'Signin' and 'Signup' pages connecting to my home page. Some advice would be really helpful. (I've attached an image of my tree structure)
I'm also getting a error - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
My app.js
// define dependencies
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 session = require('express-session');
var passport = require('passport');
var ejs = require('ejs');
var ExpressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
//handle file uploads
var upload = multer({des: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
// const PORT = 5500; // you can change this if this port number is not available
const router = express.Router();
var routes = require('./routes/index');
var users = require('./routes/users');
// app.use('/', routes);
// app.use('/users', users);
var app = express();
//view engine setup
app.use('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// Handle Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
//Express Validator middleware
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
};
}
}));
//express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
//catch 404 and forward to error handler
app.use(function(req, res, next){
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//error handlers
//development error handler
//will print stacktrace
if (app.get('env') === 'development'){
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
//production erro handler
//no stacktraces leaked to user
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// //connect to database
// mongoose.connect('mongodb://localhost:27017/auth_tuts', { //replace this with you
// // useMongoClient: true
// }, (err, db) => {
// if (err) {
// console.log("Couldn't connect to database");
// } else {
// console.log(`Connected To Database`);
// }
// }
// );
module.exports = app;
My user.js
var express = require('express');
const router = express.Router();
// GET home page.
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.get('/signup', function (req, res, next) {
res.render('signup');
});
module.exports = router;
My index.js
var express = require('express');[enter image description here][1]
var router = express.Router();
// GET home page.
router.get('/', function(req, res, next){
res.render('index', { title: 'Express' });
});
module.exports = router;
my package.json file
{
"name": "project",
"version": "1.0.0",
"description": "College Project",
"main": "app.js",
"scripts": {
"start": "node ./bin/www"
},
"repository": {
"type": "git",
"url": "git+https://github.com/KevinKerin/kjs-webdesign.git"
},
"author": "Johnathan Munster",
"license": "ISC",
"bugs": {
"url": "https://github.com/KevinKerin/kjs-webdesign/issues"
},
"homepage": "https://github.com/KevinKerin/kjs-webdesign#readme",
"dependencies": {
"bcrypt": "^3.0.2",
"body-parser": "^1.18.3",
"connect-flash": "*",
"cookie-parser": "*",
"debug": "*",
"ejs": "^2.6.1",
"express": "^4.16.4",
"express-messages": "*",
"express-session": "^1.15.6",
"express-validator": "*",
"jsonwebtoken": "^8.4.0",
"mongodb": "*",
"mongoose": "^5.3.12",
"morgan": "*",
"multer": "*",
"nodemailer": "^4.6.8",
"nodemailer-smtp-transport": "^2.7.4",
"passport": "*",
"passport-http": "*",
"passport-local": "*",
"serve-favicon": "*",
"shortid": "^2.2.14"
}
}
File Structure
Issue fixed. I had .use instead of .set(‘views’, path...)
Working on my routing now.
Given is:
/routes/index.js
var express = require('express');
var router = express.Router();
//var mongo = require('mongodb').MongoClient;
//var objectId = require('mongodb').ObjectID;
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/test';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/insert', function(req, res, next) {
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('userdata').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/');
});
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require('express-handlebars');
var expressValidator = require('express-validator');
var expressSession = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
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'))); eingetragen)
app.use(expressValidator());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: "eefa56_50cacb_34634f", saveUninitialized: false, resave: false})); // dafault storage is RAM, otherwise kann ich in der API von express-session rumwühlen, da der storage serverseitig in einer DB erfolgt
app.use('/', indexRouter);
app.use('/users', usersRouter);
...
package.json
{
"name": "sample_express_app(POST_GET_handlebars)",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"assert": "^1.4.1",
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-handlenter": "^3.0.0",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"http-errors": "~1.6.2",
"mongodb": "^3.1.4",
"morgan": "~1.9.0"
}
}
The mongoDB server is running and there is no issue to manipulate the database in the CMD. It especially deals with the router.post('/insert' ... in /routes/index.js. There is something wrong(but maybe at another point too).
I also tried it with this (either I get the error db.collection('userdata').insert(... --> 'db.collection is not a function' or db.userdata.insert(... --> 'cannot read property insert'):
1)
db.runCommand({
insert: "userdata",
documents: [ item ]
}
)
2)
db.collection('userdata').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
3)
db.userdata.insert(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
Native mongoDB driver works with the help of MongoClient.
Make changes in the index.js file
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017';
mongo.connect(url, function(err, client) {
const db = client.db(dbName);
//your db queries
})
refer mongodb
First of all sorry my bad English. I'm studying and I'm doing an academic project and came across a problem. I can not recall a session variable.
package.json
"dependencies": {
"body-parser": "^1.7.0",
"ejs": "~1.0.0",
"express": "^4.8.7",
"express-session": "^1.11.3",
"ini": "^1.3.4",
"mysql": "^2.8.0",
"winston": "^1.0.1"
}
server.js
var express = require('express');
var session = require('express-session');
var app = express();
...
require('./router/main')(app, language, connection, logger);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
main.js
module.exports = function(app, languageItems, connection, logger) {
app.post('/', require('../router/login.js')(languageItems, connection, logger));
app.get('/', require('../router/login.js')(languageItems, connection, logger));
}
login.js
module.exports = function (language, connection, logger) {
var routerTemplateLogin = function (req, res) {
var utils = require('../utils/utils');
var util = new utils.Util;
// It does not work :-(
logger.debug(req.session);
req.on('data', function(data) {
var arrayPost = util.postDataToArray(data);
});
res.render('pages/login.ejs', {
lang: language
});
}
return routerTemplateLogin;
}
In login.js see // It does not work :-(. Full project in https://github.com/braulioti/pecuniam
Thanks
The problem is that the routes are set up before any other middleware. Move this line:
require('./router/main')(app, language, connection, logger);
after this:
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
in your server.js.
This app works fine locally and works on openshift with no errors, however the views aren't rendering it is just printing the source code. I tried deleting and recreating the app but still no luck.
Here is part of my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");
var handlebars = require("handlebars");
var WebPageTest = require('webpagetest');
// Web Page Test - API key.
var wpt = new WebPageTest('www.webpagetest.org', '1234567890');
var router = express.Router();
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
/***** Views *****/
// Homepage.
app.get('/', function(req, res) {
var template = fs.readFileSync("views/index.html", "utf8");
// handlebars data, optional.
var source = {
message : "Homepage!"
};
var pageBuilder = handlebars.compile(template);
var pageText = pageBuilder(source);
res.writeHead(200, {"Context-Type": "text/html"});
res.write(pageText);
res.end();
});
/***** Start App *****/
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 5000;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
app.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ", server_port " + server_port);
});
Here is part of the package.json
{
"name": "wpt",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.10.0",
"express": "^4.10.6",
"webpagetest": "^0.3.1",
"mongoose": "^3.8.21",
"handlebars": "^2.0.0",
"express3-handlebars": "^0.5.2",
"fs":"*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
I added fs to the dependencies manually but it didn't seem to have any effect.
It's probably a lot easier to just use a handlebars Express views engine such as hbs. Example:
// ...
var hbs = require('hbs');
app.engine('hbs', hbs.__express);
app.engine('html', hbs.__express);
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
hbs.localsAsTemplateData(app);
app.get('/', function(req, res) {
res.render('index.html', {
message: 'Homepage!'
});
});
// ...