So I am using nodejs and mongodb and trying to set a cookie on one of the pages.
In the app.js file, it is pretty standard using this
var express = require('express')
, app = express()
, dbUserModel = require('./models/user')
, db = require('./db')
, pass = require('./config/passport')
, passport = require('passport')
, routes = require('./routes/index')
, user = require('./routes/user')
, path = require('path')
, http = require('http')
, connect = require('connect')
, mongoose = require('mongoose')
, mongoConnect = mongoose.connect('mongodb://localhost/test5');
// all environments
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser('secret'));
///app.use(express.cookieSession());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index)
app.get('/register', user.register);
app.post('/register', user.registerPost);
app.get('/registerError', user.registerError);
app.get('/registerThanks', user.registerThanks);
app.get('/login', user.login);
app.post('/login', user.loginPost);
app.get('/loginError', user.loginError);
app.get('/userProfile', user.userProfile);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
console.log('Users: ' + db.collections.users);
});
Then I am calling my route file.
This is my code:
exports.login = function(req, res) {
res.render('login', {user: req.user, title: 'Weblio'});
};
exports.loginPost = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) { return res.redirect('loginError'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('userProfile');
});
})(req, res, next);
};
exports.loginError = function (req, res) {
res.render('loginError', {title: 'Weblio'});
};
exports.userProfile = function(req, res) {
res.render('userProfile', {user: req.user, title: 'Weblio'});
res.cookie('name', 'test', { maxAge: 900000, httpOnly: true });
};
When I go to the userProfile page and in the console I type in document.cookie it shows an empty string as the result.
I also tried moving the res.cookie into the login post and it was not working...
Please help!