简体   繁体   中英

node.js: How can i get cookie value by cookie name from request?

How i can get cookie value by cookie name?

res.headers['set-cookie'] returns all cookies.

i need like res.headers['set-cookie']['cookieName']

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;
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM