How can I make session variables accessible to sub application - javascript

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.

Related

Nodejs and mongodb connection error after upgrading Mongo

Am trying to build some Todo app using Express and mongodb but i have some problems with nodejs and mongo connection and i searched about it on internet but didn't get any solution for my problem.
When trying to connect to mongodb from node js as in this code:
// This to require Express framework to use it
const express = require('express');
const csrf = require('csurf');
const errorhandler = require('errorhandler')
// Loads the piece of middleware for sessions
const logger = require('morgan');
const favicon = require('serve-favicon');
const methodOverride = require('method-override');
// This is a middleware to handle requests and parse the forms
const bodyParser = require('body-parser');
const routes = require('./routes');
const tasks = require('./routes/tasks');
const http = require('http');
const path = require('path');
const mongoskin = require('mongoskin');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const db = mongoskin.db("mongodb://localhost:27017/todo");
// Define object of express
const app = express();
app.use((req, res, next) => {
req.db = {};
req.db.tasks = db.collection('tasks');
next();
});
// This makes us can access app name from any JADe template
app.locals.appname = "Todo App Express.js";
app.locals.moment = require('moment');
// set app port to 8081 port
app.set('port', 8081);
// these tells express where's project safe templates in, and tell what's
// their extension will be.
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// show express favicon in browser
app.use(favicon(path.join('public', 'favicon.ico')));
// this will print requests in terminal
app.use(logger('dev'));
// using body parser to can parse requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
// to use CSRF we need cookie parser
app.use(cookieParser('CEAF3FA4-F385-49AA-8FE4-54766A9874F1'));
app.use(session({
secret: '59B93087-78BC-4EB9-993A-A61FC844F6C9',
resave: true,
saveUninitialized: true
}));
app.use( csrf() );
// to process LESS stylesheets into CSS ones
app.use(require('less-middleware')(path.join(__dirname, 'public')));
// to use other static files which inside public
app.use(express.static(path.join(__dirname, '/public')));
// to make csrf used in templates
app.use( (req, res, next) => {
res.locals._csrf = req.csrfToken();
return next();
});
app.param('task_id', (req, res, next, taskId) => {
req.db.tasks.findById(taskId, (error, task) => {
if (error) return next(error);
if (!task) return next(new Error('Task is not found.'));
req.task = task;
return next();
});
});
// homepage to show our todo homepage
app.get('/', routes.index);
// list all created tasks [in-progress ones]
app.get('/tasks', tasks.list);
// this to mark all task as completed in one step
app.post('/tasks', tasks.markAllcompleted);
// this to add new task
app.post('/tasks', tasks.add);
// this to mark specfic task as completed
app.post('/tasks/:task_id', tasks.markcompleted);
// this to delete specfic task by :task_id
app.delete('/tasks/:task_id', tasks.del);
// this to list all completed tasks
app.get('/tasks/completed', tasks.completed);
// this 404 error page to show it if user requested any route doesn't exist in our routes
app.all('*', (req, res) => {
res.status(404).send();
});
if ('development' == app.get('env')) {
app.use(errorhandler());
}
// create our server
http.createServer(app).listen(app.get('port'),
() => {
console.log('Express server listening on port ' + app.get('port'));
});
I go this error in terminal:
/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:804
throw err;
^
TypeError: Cannot read property 'apply' of undefined
at EventEmitter.<anonymous> (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/collection.js:51:21)
at Object.onceWrapper (events.js:272:13)
at EventEmitter.emit (events.js:180:13)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/utils.js:134:27
at result (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:406:9)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:271:5
at connectCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:940:5)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:801:11
at process._tickCallback (internal/process/next_tick.js:112:11)
[nodemon] app crashed - waiting for file changes before starting...
And in my Firefox got :
Unable to connect
Firefox can’t establish a connection to the server at localhost:8081.
Using NodeJS V9.8.0 and mongodb v3.4.14
This was a problem even we faced and it seems it just has to do with the consequent versions of 'mongoskin'. Why don't you try and use mongodb ?
Saves time and a much better option!

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');

How to fetch images from node.js server's folder in URL?

Does anybody know how to fetch images from node.js server's folder in URL?
In my folder structure I have folder data and inside there is subfolder img with image. I want to access this image with URL, like this:
http://localhost:3000/data/img/default.jpg
but when I enter it into browser I always get this error:
Page Not Found /data/img/default.jpg is not a valid path.
server.js:
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose');
var express = require('express');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error('\x1b[31m', 'Could not connect to MongoDB!');
console.log(err);
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
app.use(express.static('data/img'));
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
express.js:
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
session = require('express-session'),
compress = require('compression'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
helmet = require('helmet'),
passport = require('passport'),
mongoStore = require('connect-mongo')({
session: session
}),
flash = require('connect-flash'),
config = require('./config'),
consolidate = require('consolidate'),
path = require('path');
module.exports = function(db) {
// Initialize express app
var app = express();
// Globbing model files
config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
require(path.resolve(modelPath));
});
// Setting application local variables
app.locals.title = config.app.title;
app.locals.description = config.app.description;
app.locals.keywords = config.app.keywords;
app.locals.facebookAppId = config.facebook.clientID;
app.locals.jsFiles = config.getJavaScriptAssets();
app.locals.cssFiles = config.getCSSAssets();
// Passing the request url to environment locals
app.use(function(req, res, next) {
res.locals.url = req.protocol + '://' + req.headers.host + req.url;
next();
});
// Should be placed before express.static
app.use(compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Showing stack errors
app.set('showStackError', true);
// Set swig as the template engine
app.engine('server.view.html', consolidate[config.templateEngine]);
// Set views path and view engine
app.set('view engine', 'server.view.html');
app.set('views', './app/views');
// Environment dependent middleware
if (process.env.NODE_ENV === 'development') {
// Enable logger (morgan)
app.use(morgan('dev'));
// Disable views cache
app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') {
app.locals.cache = 'memory';
}
// Request body parsing middleware should be above methodOverride
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// Enable jsonp
app.enable('jsonp callback');
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
// connect flash for flash messages
app.use(flash());
// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
// If the error object doesn't exists
if (!err) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not Found'
});
});
return app;
};
It's like you have already set your data/img folder as a static folder in the line below:
app.use(express.static('data/img'));
In that case, you should be accessing images placed in the static folder above using below url:
http://localhost:3000/default.jpg
I will however advice you use Node's global variable __dirname to indicate the root of the static folder but this depends on where your server.js is located within your file structure.
The js file containing the snippets below is located in the root and I have /data/img folder from the root as well and I am able to retrieve the image using /image name.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/data/img'));
app.listen(3500, function () {
console.log('Express server is listening, use this url - localhost:3500/default.png');
});
See if this helps you. If it does, make sure you know the reason for using the __dirname global variable name.
SO1

CORS header not working in MEAN stack application

I am developing an application using the MEAN stack (Node.js, Express, AngularJS, and Mongoose). I have a basic understanding of the two. My API is running on a different port from my frontend, and because of this, I've included the CORS header in my API file. However, Chrome is still giving me this error:
XMLHttpRequest cannot load http://localhost:9000/#/.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is the header I've included in my API:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I have no idea where I'm going wrong. If it helps at all, I'm trying to load a user object in order to display information on a profile page. This is the code from my Profile Controller:
angular.module('angTestApp')
.controller('ProfileCtrl', function ($scope, $http) {
$http.get('http://localhost:8080/profile')
.success(function (user) {
$scope.user = user;
console.log(user);
});
});
EDIT
Here's my server.js file if that helps:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var cors = require('cors');
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://test:test#novus.modulusmongo.net:27017/a3pemoGa')
var classroom = require('./app/models/classroom');
var article = require('./app/models/article');
var user = require('./app/models/user');
//From Tutorial
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());
app.use(cors());
//app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
//From tutorial
// set up our express application
require('./app/config/passport')(passport); // pass passport for configuration
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.set('view engine', 'ejs'); // set up ejs for templating
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // 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
require('./app/API/routes')(app, passport);
//require('./app/API/general');
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
//exports = module.exports = app;
i resolved the cors issue with tricky solution . first create the the route of scrape like this with require "REQUEST" npm
app.get('/scrape', function (req, res) {
console.log("=============================Scrape =========================")
var url = req.body.url;
request(url, function(error, response, html){
if(!error){
res.send(html)
}
});
and in the frontend use like this
$http.get("/scrape", {
params: { "url": "http://localhost:8080/profile" }
});

Categories