Sai Krishnadas
Sai Krishnadas

Reputation: 3419

couldn't get the cookie nodejs

I set a cookie with,

router.get("/addCartToCookie", function(req, res) {
  let options = {
    maxAge: 1000 * 60 * 15,
    httpOnly: true, 
  };

  let cartData = {
    name: "test cookie",
    slug: slugify("test cookie"),
    productPictures: "K6B4dzGjN-teal.jpeg",
    price: 200,
    description: "testing cookies",
    quantity: 7,
  };

  // Set cookie
  res.cookie("cartName", cartData, options); 
  res.send("Cart Added to Cookie");
});

Which perfectly sets a cookie named "cartName". But once I try to get the cookie, It shows "cartName" is undefined.

Get Cookie Code:

router.get("/getCartFromCookie", function (req, res) {
  res.send(req.cookies["cartName"]);
  console.log(req.cookies);
});

I tried console logging the cookies but it also shows undefined.

Upvotes: 1

Views: 844

Answers (2)

kevintechie
kevintechie

Reputation: 1521

You don't show all your code, but I assume you're using the cookie-parser middleware to access the cookies directly on the request object. If not, start by adding cookie-parser and go from there.

For your cookie reading issue, be aware that you can't send and read cookies on the same request. You need one request to set the cookie and another to read the cookie.

import express from 'express';
import cookieParser from 'cookie-parser'
import {inspect} from 'util';

const app = express();
const router = express.Router()
router.use(cookieParser())
app.use(router);

const port = 3000

router.get('/setcookie', (req, res) =>{
  res.cookie('testCookie', 'magic content');
  res.send("set the cookie");
})

router.get('/readCookie', (req, res) =>{
  res.send('your cookies: ' + inspect(req.cookies['testCookie']));
  console.log(req.cookies);
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Upvotes: 2

Salvino D'sa
Salvino D'sa

Reputation: 4506

From what I know, the optimized way of handling cookies is by using cookie-parser dependency for express.

$ npm install cookie-parser

Then you could easily fetch your cookies using req.cookies or req.signedCookies property like below:

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function (req, res) {
  // Cookies that have not been signed
  console.log('Cookies: ', req.cookies)

  // Cookies that have been signed
  console.log('Signed Cookies: ', req.signedCookies)

  // Your cart cookie
  console.log('Cookies: ', req.cookies.cartName)
})

app.listen(8080);

References:

  1. https://github.com/expressjs/cookie-parser
  2. http://expressjs.com/en/resources/middleware/cookie-parser.html

Upvotes: 1

Related Questions