Get and Set a Single Cookie with Node.Js Http Server

Get and Set a Single Cookie with Node.js HTTP Server

There is no quick function access to getting/setting cookies, so I came up with the following hack:

const http = require('http');

function parseCookies (request) {
const list = {};
const cookieHeader = request.headers?.cookie;
if (!cookieHeader) return list;

cookieHeader.split(`;`).forEach(function(cookie) {
let [ name, ...rest] = cookie.split(`=`);
name = name?.trim();
if (!name) return;
const value = rest.join(`=`).trim();
if (!value) return;
list[name] = decodeURIComponent(value);
});

return list;
}

const server = http.createServer(function (request, response) {
// To Read a Cookie
const cookies = parseCookies(request);

// To Write a Cookie
response.writeHead(200, {
"Set-Cookie": `mycookie=test`,
"Content-Type": `text/plain`
});

response.end(`Hello World\n`);
}).listen(8124);

const {address, port} = server.address();
console.log(`Server running at http://${address}:${port}`);

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

How can I set cookie in node js using express framework?

The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.

If express.static is handling the request, you need to move your middleware up:

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});

// let static middleware do its job
app.use(express.static(__dirname + '/public'));

Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next() when the cookie has been set.

Update

As of now the cookie parser is a seperate npm package, so instead of using

app.use(express.cookieParser());

you need to install it separately using npm i cookie-parser and then use it as:

const cookieParser = require('cookie-parser');
app.use(cookieParser());

How can i set or get cookies at server side in nodejs?

You can use this package to manage cookies https://www.npmjs.com/package/cookies.

Here is a minimal example

var http = require('http')
var Cookies = require('cookies')

// Create a cookies object
var cookies = new Cookies(req, res, { keys: keys });
// Set the cookie to a value
cookies.set('LastVisit', new Date().toISOString(), { signed: true })

Get a cookie with nodejs

Look into using Mikeal Rogers' request module. It has built-in cookie handling, follows redirects, and other goodies. It's also a little simpler API than http.request. Your cookies should just work after logging in.

Update: Sample with request (npm install request):

var request = require("request");

request.post({url: "http://localhost:8080/jasperserver/rest/login", qs: {j_username: "jasperadmin", j_password: "jasperadmin"}}, function(err, res, body) {
if(err) {
return console.error(err);
}

request.get("http://localhost:8080/jasperserver/ressource/reports", function(err, res, body) {
if(err) {
return console.error(err);
}

console.log("Got a response!", res);
console.log("Response body:", body);
});
});

Not Able to Set Cookie using NodeJs in Browser Application tab even its coming in response

After 2 days trying every possible solution this finally worked for me

This is how you need to call the api from which you want to set the cookie.

const postHelper = async (url, body) => {
return await fetch(url, {
method: "POST",
headers: {
Accept: "applicaiton/json",
"Content-Type": "application/json",
},
body: body && JSON.stringify(body),
withCredentials: true, // should be there
credentials: 'include' // should be there
});
};

After adding this you will get CORS error so please add this line of code in your server

app.use(cors({ origin: true, credentials: true }));

And finally

res.cookie('cookieKey', cookieKey, { expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)), secure: true  });

PS - This solution will work in case of Cross domain and same domain but in case of cross domain most browsers will not allow you to set cookie until user agree.



Related Topics



Leave a reply



Submit