There is no quick function access to getting/setting cookies, so I came up with the following hack:
var http = require('http');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var cookies = parseCookies(request);
// To Write a Cookie
response.writeHead(200, {
'Set-Cookie': 'mycookie=test',
'Content-Type': 'text/plain'
});
response.end('Hello World
');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
This will store all cookies into the cookies object, and you need to set cookies when you write the head.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…