The value of req.cookies is returning as undefined, even though cookies have been

I integrated the cookie-parser module into my express app. When a user requests the root page, I use res.cookie(name, value) to set a random number on the cookie, which is working correctly (I verified this in my browser console). However, when I attempt to log req.cookie, it always returns undefined.

Below is the code snippet:

routes.js

var express = require('express')
var router = express.Router()

var movieTrailer = require('movie-trailer');

var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');

//Setting up x-ray for scraping
var Xray = require('x-ray');
var x = Xray();

var debug = false;

router.get('/', (req, res) => {
  console.log('Page requested!');
  console.log('Cookies: ', req.headers.cookies); // This line returns undefined for some reason

  var scrapeMovies = function(){
    return new Promise((resolve, reject) =>{
      fs.readFile('moviesRT.json', (err,data) =>{
        var movies = JSON.parse(data);
        resolve(movies);
      });
    });
  };

scrapeMovies().then(
    movies => {
      var randomInt = Math.floor(Math.random() * movies.length);
      res.cookie('randomInt', randomInt);
      var randomMovie = movies[randomInt];
      movieTrailer(randomMovie.title, (err, url) =>{
        console.log('Requesting trailer: ', randomMovie.title);
        if(err) throw err;
        var embedUrl = url.replace('watch?v=','embed/');
        console.log('Video ID: ', url.slice(32,url.length));
        randomMovie.trailerURL = embedUrl; 
        res.render('main',randomMovie,
        (err, html) =>
        {
          if(err) throw err;
          console.log('Rendering...');
          res.send(html);
          console.log("Done!");
        });
      });
    });

});

module.exports = router;

app.js

const express = require('express');

//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;

var routes = require('./routes');

var debug = true;

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());

//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
  if(!debug) logs.disable(); 
});

Answer №1

To access the cookies set by express, you can check req.headers.cookie.

If you prefer to use the parsed result of the cookie-parse middleware found in req.cookies, make sure to pay attention to the order in which you register your routes and middleware.

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());

The cookie parsing occurs after the execution of routes in routes.

Ensure that you place cookieParser() before the route where you intend to utilize it.

app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));

Answer №2

My issue was resolved by following these steps:

Whenever a request is sent from the client-side to the server, ensure that you include withCredentials: true. Here's an example:

{
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
    'withCredentials':true
  };

Answer №3

This incident occurred to me when I made a PUT request from the client-side (using Angular) without including the body object.

I made this mistake by omitting the second argument:

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}

Instead of the correct way, like this:

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}

Answer №4

In order to access the cookies, you should use req.cookies['cookie-name'] for reading them and

res.cookie('cookie-name', 'cookie-value')
for setting them.

Answer №5

Success story!

If you're working on the front end, make sure to include credentials : 'include' in your fetch API settings.

For those interested, here's a more detailed example for a GET request:

fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //manipulate the data)
.catch(err => console.log(err.message));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having trouble adding a second image. The functionality only seems to work for the first image input

How come I can't access the second file chooser when the first one works perfectly fine? This section contains HTML code <form action="<?php url("image/uploadImg"); ?>" method="post" en ...

Stunning Opening and Closing Animation with Ajax

Looking for help with creating an animation like the one shown here: Incorporating this into my current site at: dageniusmarketer.com/DigitalWonderland/ I want the window displaying text content to open and close as users navigate through the links, ess ...

Breaking down numerous requests into chunks in JavaScript: A step-by-step guide

I am facing a situation where I have multiple requests to make, but they cannot all be called simultaneously. Therefore, I came up with a solution to split the set of requests into chunks of 10. I'm curious about how I can handle making these 10 reque ...

Ways to Modify the Additional Text with AngularJS

I'm encountering difficulties with the append event when adding each name from a single input field instead of using ng-repeat. Can anyone provide guidance on how to achieve this without relying on ng-repeat? Unfortunately, ng-repeat is not functionin ...

Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect. Fiddle: http://jsfiddle.net/ddac ...

The Bootstrap tooltip effectively fades away after displaying text, but it is not positioned correctly above the icon

Having some issues with my tooltip functionality. It seems to display the text on the left side and fades away upon mouseover, but it doesn't show up in a proper tooltip box over the icon as expected. I suspect that there might be a conflict between j ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

Instructions on eliminating the chosen value from the initial dropdown to ensure it does not appear in the second dropdown, with the value retrieved directly from the database. [Laravel]

<div class="form-group mb-3"> <label for="">item 1 </label> <select name="item1" class="js-example-basic-single" style="width: 100%;"> ...

Combining multiple events into one function using jQuery

I am searching for the opposite of what everyone else is seeking. I have an anonymous jQuery function that I want to keep as it is, but I need to attach multiple event handlers to it on different occasions (specifically two events). When the text inside ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

Modify a JavaScript object in JSON format using another object as reference

Consider two JSON formatted JavaScript objects: obj1 = { prop1: 1, prop2: 2, prop3: 3 } obj2 = { prop1: 1, prop2: 3 } In the context of jQuery or Angular, what is the recommended practice to update obj2 into obj1 while also re ...

"Exploring ways to pass live data from the controller to the view in CodeIgniter for dynamic chart values

I currently have the following code where I am statically assigning values. Now, I need to dynamically retrieve values and display a chart. I want to populate the 'items' variable from the controller in the same format, and then display the chart ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...

Creating, customizing, and assigning values to data attributes in Draft-js blocks: A complete guide

My current setup involves a DraftJS editor displayed like this: <Editor editorState={this.state.editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder="Write a tweet..." ref="editor" spellCheck={true} /&g ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Get the jsonarray file using express, node, and angular by downloading it

Within my web application, I am generating jsonarray files. These files have a structure similar to this: [{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}] I need to send these jsonarray files to the client for ...

Using HTML, jQuery, and JSON with an AJAX call to populate two web tables stacked on top of each other

I am encountering an issue with populating two tables using two searches based on user input in mySQL-JSON-AJAX. When the user enters a search term and clicks the corresponding button, data should populate the respective table. The problem arises when clic ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

I am curious about the distinction between two closures

Can someone please explain the distinction between these two closure examples? (function(window, undefined) { // JavaScript code })(window); Here's another example: (function(window) { // JavaScript code })(window, undefined); ...