Node.js HTTP GET/SET Cookie


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var http = require('http');

http.OutgoingMessage.prototype.setCookie = function(name, value, options) {
var cookieString = [name + "=" + value];

if (options) {
if (options.expires) {
expiresDate = new Date();
expiresDate.setDate(expiresDate.getDate() + options.expires);

cookieString.push("expires=" + expiresDate.toUTCString());
}

if (options.domain) cookieString.push("domain=" + options.domain);
if (options.path) cookieString.push("path=" + options.path);
if (options.secure) cookieString.push("secure");
if (options.httpOnly) cookieString.push("httponly");
}

this.setHeader("Set-Cookie", cookieString.join(";"))
}

http.IncomingMessage.prototype.getCookie = function(name) {
var cookies = {};

if (this.headers.cookie) {
this.headers.cookie.split(';').forEach(function(cookie) {
var pairs = cookie.split('=');
cookies[pairs[0].trim()] = (pairs[1] || '').trim();
});
}

return cookies[name] || null;
}

http.createServer(function(req, res) {
res.setCookie("abc", "123", {
expires: 30
});

res.end("Current cookie of abc: " + req.getCookie("abc"));
}).listen(3000);

console.log("Server running at http://localhost:3000");