Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda