var express = require('express')
var router = express.Router();
I am debugging my Node app and express is defined, but after stepping over the var router line, router is still undefined, how could this happen?
Well here is all the code if you must:
var express = require('express')
// , fancy_scripts = require('./fancy_scripts')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/sparks');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/fancy_scripts'));
app.use('/fancy_scripts', express.static(__dirname + '/fancy_scripts'));
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
//var router = express.Router();
//
///* GET home page. */
//router.get('/', routes.index);
If were to guess the line app.use(app.router);
might be the culprit...?
Related
When using express.static() in the code below I get an error telling me that the function doesn't exist.
This is my code:
var app = require("express");
var consign = require("consign");
var bodyParser = require("body-parser")
var expressValidator = require("express-validator");
var express = app();
express.set('view engine', 'ejs');
express.set('views', './app/views');
express.use(express.static("./app/public"));
express.use(bodyParser.urlencoded({extended: true}));
express.use(expressValidator());
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(express);
module.exports = express;
var express = require("express"); // !!!
var consign = require("consign");
var bodyParser = require("body-parser")
var expressValidator = require("express-validator");
var app = express(); // !!!
app.set('view engine', 'ejs');
app.set('views', './app/views');
app.use(express.static("./app/public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app); // !!!
module.exports = express;
https://expressjs.com/en/starter/static-files.html
Eu falo inglês, desculpe. Eu normalmente daria uma explicação.
English: I speak English, sorry. I would usually give an explanation.
EJS Error: Failed to lookup view "admin_landing2" in views directory "/Users/aryanarora/Desktop/asn3/views".
while trying make a call to localhost/8080/yolo
I am getting the same error even if I switch to hbs. (i have installed both the packages)
var express = require("express");
var app = express();
var port = process.env.PORT || 8080;
var path = require('path');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var fs = require('fs');
// const hbs = require('hbs');
// hbs.registerPartials(__dirname + './views');
// app.set('view engine','hbs');
// Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
var users = [];
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', function(req,res,next){
console.log(req.method, 'request:', req.url);
next();
});
app.locals.yolo = require('./Data/courses.json');
//Request i am trying to get//
app.get('/yolo',function(req,res){
//res.sendFile(path.join(__dirname + '/admin_landing2.hbs'));
res.render('admin_landing2', {var1 : "pehla" , var2 : "dusra"});
});
app.get('/login', function(req,res){
res.sendFile(path.join(__dirname + '/admin_login.html'));
var filepath = './admin_login.html';
console.log(filepath);
});
The problem is that you're setting the views directory to the wrong location.
Do
app.set('views', __dirname)
instead of
app.set('views', path.join(__dirname, 'views'))
Well, as the title suggests, I broke everything using socket.io. Mainly because the way it calls express breaks everything else using express.
Here is my old way of doing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Which works wonders! It works, however adding socket.io like so:
/*jshint esversion: 6*/
const app = require('express')();
const http = require('http').Server(app);
const socket = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
// app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Breaks everything using express.* because it is saying express is not defined. So my static path gets broken and of course the app crashes.I tried several solutions, but to no avail.
Oops forgot to add the error:
app.use(express.static(path.join(__dirname, 'static')));
^
ReferenceError: express is not defined
Try this. The idea is that you need to import express. Socket.io can be required once the rest is defined.
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// Init socket
const socket = require('socket.io').listen(server);
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
I have only realised that this has been happening.
My stack:
NodeJS
Express
PassportJS
Angular
MongoDB with Mongoose
When I log into my website, I see that the collection sessions is created, with one record (as one would expect). Then, I navigate around the website and noticed that my sessions have goes to 13 records. Then, I navigate some more and I see that it has gone over 27.
What in the world is going on? Am I doing something that is causing this?
My main app.js file is below:
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(session({secret:config.sessionSecret, saveUninitialized:true, resave:true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});
Each one of my sessions look like the below (if it helps in any way):
{
"_id": "cSqLjOGJlYBvNLYJ8v6zXqtqzuIcGwbx",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"}}",
"expires": "2017-10-10 22:46:09",
"lastModified": "2017-09-26 22:46:09"
}
Try this
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(passport.initialize());
app.use(passport.session());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});
i'm trying to use Mongo-Express to lookup my mongoDB, I newbee, after i went under the user and pass i got error -> Cannot GET /
var express = require('express')
, routes = require('./routes')
, http = require('http');
var _ = require('underscore');
var async = require('async');
var utils = require('./utils');
var mongodb = require('mongodb');
var cons = require('consolidate');
var swig = require('swig');
var swigFilters = require('./filters');
var app = express();
var config = require('./config');
//Set up swig
app.engine('html', cons.swig);
Object.keys(swigFilters).forEach(function (name) {
swig.setFilter(name, swigFilters[name]);
});
//App configuration
app.configure(function(){
if(config.useBasicAuth){
app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password));
}
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(config.site.baseUrl,express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser(config.site.cookieSecret));
app.use(express.session({
secret: config.site.sessionSecret,
key: config.site.cookieKeyName
}));
app.use(express.methodOverride());
app.use(app.router);
});
First of all, try to learn from actual/updated tutorials. Actual express version is 4, and it removes:
app.use(app.router);
(therefore my deduction of outdated tutorial)
Second thing, i dont see in your code any routes. If you want to get responses from server, you need to write routes. For example:
app.get('/test', function(req, res) {
res.send('Hello from route');
});