Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

373
Vistas
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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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
about 4 years ago · Juan Pablo Isaza Denunciar

0

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}`)
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda