Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

How i can get cookie value by cookie name?

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

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

like image 600
FunnyCheese Avatar asked Aug 12 '18 20:08

FunnyCheese


People also ask

How do I read cookie data in node JS?

We can check cookies by visiting localhost:3000/setcookie. This will show a message as cookies are added. We can check the cookies by visiting localhost:3000/getcookie. Now we can see that our cookies are added to the cookies object as shown above.

How do you retrieve the data from the cookies?

get() The get() method of the cookies API retrieves information about a single cookie, given its name and URL. If more than one cookie with the same name exists for a given URL, the one with the longest path will be returned.

How do you parse cookies in Express JS?

Now to use cookies with Express, we will require the cookie-parser. cookie-parser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index. js file; this can be used the same way as we use other middleware.


1 Answers

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.

like image 170
Rajan Lagah Avatar answered Sep 16 '22 15:09

Rajan Lagah