node.js: How can i get cookie value by cookie name from request?
I have found this solution may work for you
var get_cookies = function(request) {
var cookies = {};
request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
var parts = cookie.match(/(.*?)=(.*)$/)
cookies[ parts[1].trim() ] = (parts[2] || '').trim();
});
return cookies;
};
and then you can use
get_cookies(request)['cookieName']
But if you are using express.I will suggest you
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
then to get cookie value.You can
req.cookies['cookieName']
Hope this help. I found these solutions and worked for me.
Typescript version of Rajan Lagah
's answer with some more checks:
const getCookiesAsCollection = function (rawCookie: string): Record<string, string> {
const cookies: Record<string, string> = {};
rawCookie && rawCookie.split(";").forEach(function (cookie: string) {
const parts: RegExpMatchArray | null = cookie.match(/(.*?)=(.*)$/);
if (parts && parts.length) {
cookies[parts[1].trim()] = (parts[2] || "").trim();
}
});
return cookies;
};