edit - this requires Express, didn't notice that your question was not tagged express. if you aren't using express you may want to look at the connect.session
example, this is what express uses behind the scenes to populate req.session
.
Depending on exactly what you want to do with the data, you might prefer to use req.session
to store temporary information until the client closes the window or their cookie times out. Here's an example that keeps track of the address across future requests:
var express = require('express');
var app = express();
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret:'$tackoverflow-rules'}));
app.get('/', function(req, res){
if(req.session.address === undefined){
res.send(200,'<html><body><form action="address" method="post">'
+'<input type="text" name="address" placeholder="Enter address">'
+'</form></body></html>');
} else {
res.send(200,'<html><body><span>I know that you live at '+req.session.address+'!</span></body></html>');
};
});
app.post('/address', function(req, res){
if(req.body.address !== undefined && req.body.address !== ""){
req.session.address = req.body.address;
res.redirect('/');
} else {
req.session.address = undefined;
res.redirect('/');
};
});
require('http').createServer(app).listen(3000);