I have an AngularJS client sending POST form data to an Express server using the $http()
function. I want the server to set a cookie in the client holding the user's email address. This is all I'm storing, so I don't need the more powerful server-side sessions. I'm just using the cookie-session
module.
Problem: The cookie is not persisting in the client. Subsequent requests from the same client show an empty session variable.
I've seen the example here and am using req.session.save()
after setting the cookie, but it still doesn't work.
Server code:
// server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session')
var methodOverride = require('method-override');
// Configuration
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));
var express = require('express');
var app = express();
// Cookies
app.use(cookieParser());
app.use(cookieSession({
name: 'session', // what should this name match?
resave: true,
saveUninitialized: true,
keys: ['key1', 'key2'] // what do these values need to match?
}));
app.use(function(req, res, next) {
// Create a cookie.
console.log("Session user [before set]: %j", req.session);
req.session.mycookie = "sample data"; // simplified example for illustration
console.log("Session user [after set]: %j", req.session);
// Save session cookie
req.session.save();
});
app.listen(3000);
Every request from the same client gives the output:
Session user [before set]: {}
Session user [after set]: {"mycookie":"sample data"}
Subsequent tests by the client show the cookie is not persisting. I even used the Firefox "View Cookies" plugin to check if any cookies are created, and non were.
1. Why is my cookie not persisting? I am new with Express, so I could be missing something obvious.
2. Am I using the correct parameters to create the cookieSession? I'm not sure what keys
or name
should be. The cookie-session
documentation is vague about this, and I couldn't find better documentation elsewhere.