0

I wanted to remember the last page someone visited (like here)
I tried to do it with cookie-session but It's doesn't work as I a suppose.

I saw this and I tried this example for extending the session without success.

Here the code :

var session = require('cookie-session');
var express = require('express');

var app = express();

app.use( session({ secret: 'secret' }) );


app.get('/a', function (req, res) {
  if(req.session.last) {
    res.write("the last page was " + req.session.last + ". ");
  }  
  req.session.last = "a";
  res.end("Page A");  
});

app.get('/b', function (req, res) {
  if(req.session.last) {
    res.write("the last page was " + req.session.last + ". ");
  } 
  req.session.last = "b";  
  res.end("Page B");
});

app.get('/c', function (req, res) {
  if(req.session.last) {
    res.write("the last page was " + req.session.last + ". ");
  } 
  req.session.last = "c";  
  res.end("Page C");
});

app.listen(8080);
Community
  • 1
  • 1
Tittouns
  • 3
  • 3

1 Answers1

0

Are you sure you are not getting an error in your logs along the line of "cannot write to headers after they have been sent"? Can you try moving the assigning of the session to before the res.write call? From your first link, in the comments...

"I kept getting an error that the headers couldn't be set after they'd been sent. I modified the code so that lastPage was set before sending any body eg:

var responseText;

if(req.session.lastPage) 
responseText = 'Last page was: ' + req.session.lastPage + '. ';

else
responseText = 'You\'re Awesome';

req.session.lastPage = '/awesome';
res.send(responseText);
Rap
  • 6,851
  • 3
  • 50
  • 88
  • Thanks You, It works now. I understand that I have to change my `req.session` before I send the response. But I don't understand why I didn't get a error. Maybe because I didn't try to write to headers but just tried to modified the session in the request – Tittouns Feb 10 '16 at 13:10
  • Because it stores all the info in the cookie. So if you change the info, the cookie is rewritten.. Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maxium cookie size limits on different browsers. The RFC6265 specification reccomends that a browser SHOULD allow At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes) In practice this limit differs slightly across browsers. See a list of browser limits here. As a rule of thumb don't exceed 4093 bytes per domain. –  Feb 10 '16 at 16:15
  • Thanks you for your complement. So data is into the session and stored into the cookies . Can we get the data from the cookies in server-side. I'm trying with cookie-parser but I can just get a express:sess and express:sess.sig – Tittouns Feb 11 '16 at 15:27