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);
To avoid double status setting (200 and 301, I'm not sure if it is possible) You can render html page with META tag HTTP-EQUIV="Refresh"
instead of redirectig status, eg
var jsrender = require('node-jsrender');
(..)
res.writeHead(200, {'Set-Cookie': cookie, 'Content-Type': 'text/plain'});
// 301 redirection replaced by rendering html template with redirection inside
var tmpl = jsrender.loadFileSync('#redirectTemplate', 'templates/redirect.html')
res.end( tmpl.render() );
And redirect.html
looks like this
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=/redirect-url">
</head>
</html>
To redirect a client after setting a cookie without Express
, just pass the URL you want to redirect to, to res.address
.
var url = "https://someurl.com";
res.address(url);
res.end();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.