I want to be able to set a cookie and then redirect the client with node.js
, without using Express
or another third party library. Online I can only find examples using Express
.
When I try to set the cookie and redirect the client, the cookie does not get set. But when I comment out the redirect, res.writeHead(301, {Location: serverAddress});
, the cookie gets set, but there is no redirect.
So how do I set a cookie and then redirect the client using straight node.js
?
var fs = require("fs");
var http = require('http');
var home = fs.readFileSync('random.html');
var serverAddress = "http://yourIpAddress";
http.createServer(function(req, res) {
if(req.url === '/favicon.ico') {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
} else if(req.headers.cookie) {
console.log("Got cookie");
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.write(home);
res.end();
} else {
console.log('Creating Cookie');
var cookie = {
"some": "data"
};
res.writeHead(200, {'Set-Cookie': cookie, 'Content-Type': 'text/plain'});
res.writeHead(301, {Location: serverAddress});
res.end();
}
}).listen(80);