I would like to use the req.flash that was removed as of Express 3.0. According the docs, simply configure the app as so to use it:
app.configure(function() {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
});
However, I've configured my app as so:
app.configure('production', function() {
app.use(express.static('/static', express.static(__dirname + '/lib/static')));
app.use(express.errorHandler());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
I've been trying to detect the availability of flash as so:
app.all('/*', function(req, res, next) {
console.log('FLASH: ', req.flash);
....
My logs show the following:
FLASH: undefined
FLASH: undefined
FLASH: function _flash(type, msg) {....
This was displayed with just one request to the '/' route. I understand why there may be multiple requests with the one GET request to '/', however, I'm wondering why req.flash is not available on every request as the docs state.
I think you should change your configuration to:
app.configure('production', function() {
app.use(express.errorHandler());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('/static', express.static(__dirname + '/lib/static')));
app.use(app.router);
});
I always keep my static route at the end of my middleware.
I think the problem is that your /* route is also firing for /static requests and, since that middleware is declared before the flash() middleware, the request object hasn't yet been modified.
Related
I was reading in upgrading to express 4 that the order of app.use has to come after my app.get and app.post routes.
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'hjs');
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
//app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
app.use(cookieParser());
//app.use(express.json());
//app.use(express.urlencoded());
app.use(session({
secret: 'keyboard cat',
saveUninitialized: true,
resave: true
}));
//authentication
app.get('/app', ensureAuthenticated,appRoutes.app);
app.get('/app/:name', ensureAuthenticated,appRoutes.main);
app.get('/views/app/:name', ensureAuthenticated, appRoutes.index);
app.get('/views/app/:name/*', ensureAuthenticated, appRoutes.partials);
app.get('/',routes.home);
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
I upgraded and now my passport authentication is not working. I moved it above the routes and below and either way I get no error just does not authenticate and set a session.
I was reading in upgrading to express 4 that the order of app.use has to come after my app.get and app.post routes.
Nonsense ! Where did you read that ?
The only thing that comes close to what you're saying is this line from Expres 3.x to 4.x Migrating Guide :
app.router has been removed. Middleware and routes are now executed in the order they're added. Your code should move any calls to app.use that came after app.use(app.router) after any routes (HTTP verbs).
But it does not mean that every app.use call should go after the routes (HTTP Verbs). Only the ones that you used to put after app.use(app.router) in your old Express 3.x code. Is that more clear ?
Regarding your issue, from Passport's docs :
Note that enabling session support is entirely optional, though it is
recommended for most applications. If enabled, be sure to use
express.session() before passport.session() to ensure that the login
session is restored in the correct order.
So you should change :
app.use(passport.initialize());
app.use(passport.session());
//app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
app.use(cookieParser());
//app.use(express.json());
//app.use(express.urlencoded());
app.use(session({
secret: 'keyboard cat',
saveUninitialized: true,
resave: true
}));
to :
//app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
app.use(cookieParser());
//app.use(express.json());
//app.use(express.urlencoded());
app.use(session({
secret: 'keyboard cat',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
Hope that helps.
Problem in accessing flash messages on view in node.js
In my Controller
this.req.flash('info','successfully submited');
this.redirect("/home");
In my home view I am not able to get flash messages as
req.flash('info');
EDIT
In controller
self.req.flash('message','hello');
In view
<%= req.flash('message) %>
In server.js
app.configure(function (){
app.use(express.cookieParser());
app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
app.use(passport.initialize());
app.use(locomotive.session());
app.use(flash());
app.use(passport.session());
app.use(app.router);
app.dynamicHelpers({ messages: require('express-messages') });
});
I have the locomotive framework.
Please see tempdata example https://github.com/MKxDev/TempData
var tempData = require('tempdata');
var app = express();
app.configure(function() {
...
// This has to appear BEFORE the router
app.use(express.cookieParser());
app.use(express.session({ secret: 'your_super_secret_session_key' })); // please change this!
app.use(tempData);
...
});
...
// Routes
app.get('/', function(req, res) {
// Retrieve tempData value here. It won't exist unless the request
// was redirected
var tempVal = JSON.stringify(req.tempData.get('test_val'));
res.render('index', { title: 'Express', temp: tempVal });
});
app.post('/', function(req, res) {
// Set tempData value here
req.tempData.set('test_val', { x: 'Hello World!' });
res.redirect('/');
});
Move your app.use(flash()) higher in the order...see below. Flash needs to be initialized before passport so that flash is recognized and available to passport.
app.configure(function (){
app.use(express.cookieParser());
app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
app.use(flash()); // moved this up a few lines
app.use(passport.initialize());
app.use(locomotive.session());
app.use(passport.session());
app.use(app.router);
app.dynamicHelpers({ messages: require('express-messages') });
});
I am setting a session cookie as part of PassportJS. I can see the connect.sid cookie being passed to the browser, and back to the application on subsequent HTTP requests.
However, when I read req.cookies in one of my routes, it is empty. I have set up express.cookieParser(), express.session(), and passport.session() in configuration settings. Is there anything else that needs to be done in order to use cookies in Express / Node?
Here are my app configuration settings:
app.configure(function () {
app.set("db_url", config.db[app.settings.env]);
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: "keyboard cat"}));
app.use(passport.initialize());
app.use(passport.session());
app.use(users);
app.use(orgs);
app.use(errorHandler);
});
Thanks!
Try req.session instead req.cookies. If you want to store information within the cookie you need to set them similar to
res.cookie('remember', 1, { maxAge: 60 * 1000 });
Then req.cookies should contain
{ remember: '1' }
The default value of req.session is
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
}
}
I'm trying to set cookie on express.js but it return undefined.
I've searched many web pages and put express.cookieParser() above app.use(app.router)
but it still can't return the right value.
app.js
app.configure(function(){
var RedisStore = require('connect-redis')(express);
app.use(express.logger());
app.set('view options', { layout: false });
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser({uploadDir: './uploads/tmp'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: "william", store: new RedisStore }));
//Initialize Passport! Also use passport.session() middleware, to support
//persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
//app.router should be after passportjs
app.use(app.router);
app.use(express.compiler({ src: __dirname + '/public', enable: ['less']}));
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true})
});
app.get('/test', function(req, res) {
res.send('testcookie: ' + req.cookies.cart);
});
the result:
testcookie: undefined
Cookies are set in HTTP Headers. res.cookie() just sets the header for your HTTP result, but doesn't actually send any HTTP. If your code was syntactically correct and it ran, it would actually just sit and not return anything. I also fixed some syntax bugs in your code in this app.get():
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true});
res.send('Check your cookies. One should be in there now');
});
You need to send something out, or at least call res.end(), after setting the cookie. Otherwise all res.cookie() does is add some headers to a list of headers that will be sent out later.
Set cookie name to value, where which may be a string or object converted to JSON. The path option defaults to "/".
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
Here is the Link for more detail
http://expressjs.com/api.html#res.cookie
total node.js noobie, started playing with demo codes from various tutorials and websites and I noticed something that I do not understand...
namely, if I have index.html in my /public folder, then
app.get("/", function (req, res) {
console.log("get /");
res.redirect("/test.html");
});
is simply never called. As soon as I rename index.html to index2.html then the method is called and I am redirected to /public/test.html
this is what I have:
var io = require('socket.io'),
express = require('express'),
MemoryStore = express.session.MemoryStore,
app = express.createServer(),
sessionStore = new MemoryStore();
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'secret',
key: 'express.sid'
}));
app.use(express.static(__dirname + '/public'));
});
and the rest is pretty much taken from this tutorial: http://www.danielbaulig.de/socket-ioexpress/
The same issue appears with any other file. If i have /public/test.html, then when I call
http://localhost:8201/test.html
this app.get is not called:
app.get("/test.html", app.authenticateUser, function (req, res) {
console.log("get /test.html");
res.redirect("/test2.html");
});
When I remove the test.html then I get forwarded to test2.html...
The reason I am trying to redirect is if the user is not logged in I do not want him to open index.html but rather want to forward him to login.html, which is not possible if index.html exists. The only "solution" is to do it client side which sucks, I don't want index.html to load in the clients browser just to forward him to login.html, the server should, in my oppinion, handle that.
Problem is your static file middleware app.use(express.static(__dirname + '/public')) is "in front" of your router. When you write
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'secret',
key: 'express.sid'
}));
app.use(express.static(__dirname + '/public'));
});
this is equivalent to
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'secret',
key: 'express.sid'
}));
app.use(express.static(__dirname + '/public'));
app.use(app.router); //Express implicitly appends router middleware!
});
because Express implicitly appends router middleware at the end of stack if you don't add it somewhere explicitly. Now you clearly see that static file middleware is in front of router. If static file is found it is served by app.use(express.static(__dirname + '/public')) and router app.use(app.router) is never called. If you want your request to always pass through router you should put it in front, for example
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'secret',
key: 'express.sid'
}));
app.use(app.router); //Now router comes first and will be executed before static middleware
app.use(express.static(__dirname + '/public'));
});
It's because express filters the request before it gets to your code. It finds the file and returns it to the browser.
Solution is either to send an event via socket.io telling the code in user's browser to redirect or move file into private space (outside public directory) and serve it via "fs" as CydGy suggested.
this very good tutorial (http://www.danielbaulig.de/socket-ioexpress/) deals on sockets.
And i thinks isn't useful for this case.
So, look this:
app.get("/test.html", app.authenticateUser, function (req, res) {
but where is the app.authenticateUser ?
it is surely he who blocks
So, replaces it by:
app.get("/test.html", function (req, res) {
or modify your app.authenticateUser.
(And use the module fs to read your file, and then, you can res.send(file);)
Don't forget to write .html in your url, else, you have to replace "/test.html" by "/test")
I hope it will help you.
It is because the below code is never called!
app.get("/", function (req, res) {
console.log("get /");
res.redirect("/test.html");
});
As app.use(app.router); is depreciated.All you got to do is write your code above this line
app.use(express.static(__dirname + '/public'));
Should be something like this
app.get("/", function (req, res) {
console.log("get /");
res.redirect("/test.html");
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res)...
Try this
app.get('/', function (req, res)...
Uri path must be ' single quoted.