javascript - Set cookie and redirect, without express -
i want able set cookie , redirect client node.js
, without using express
or third party library. online can find examples using express
.
when try set cookie , redirect client, cookie not set. when comment out redirect, res.writehead(301, {location: serveraddress});
, cookie gets set, there no redirect.
so how set cookie , redirect 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 redirect client after setting cookie without express
, pass url want redirect to, res.address
.
var url = "https://someurl.com"; res.address(url); res.end();
Comments
Post a Comment