0

I am trying to read the browser cookies on form submit. cookie-parser returns an empty cookie object, however in my browser I can see there are plenty of cookies set. This is my code:

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const testform = require("./nodejs/testform.js");

const app = express();
const cookies = require("cookie-parser");

const fromFolder = path.join(__dirname, process.env.FOLDER);
const toFolder = path.join(__dirname, "/");
console.log("from: ", fromFolder);
console.log("to: ", toFolder);

app.set("port", process.env.PORT || 5000);

app.use(express.static(fromFolder));
app.use(cookies());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function(req, res) {
  console.log(req.cookies);  // outputs "{}" <----
  testform.doSomething(req, res);
});

app.listen(app.get("port"), function() {
  console.log("Node app is running on port", app.get("port"));
});
Beppe
  • 225
  • 3
  • 10
  • 1
    Are those cookies are sent by your server? The cookies which are sent by your server will be returned to your express server. Tell more about which cookies you found in the browser. – Akhil P Apr 23 '18 at 10:37

2 Answers2

2

It appears you're doing everything correctly. However, it is important to understand that your browser will not send all cookies with every request. For example, it will not send cookies that:

  1. Have a scope that doesn't match (EG not the same domain/path as the current page)
  2. Are expired

I would suggest setting a cookie that matches your current domain in the console. EG navigate to localhost:3000 or wherever you can access your Express server. Then you can use a function like this in the console to set the cookie (thanks to https://stackoverflow.com/a/24103596/3084820):

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

setCookie('hello', 'world', 10);

Refresh your page, or navigate to another link on localhost:3000 (or wherever your server can be found.)

You should see your cookie received server-side.

MDN has some good docs on scope of cookies etc: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
  • Thanks! It was indeed a scope problem, because it was a cookie from a different domain. Instead of using cookie-parser, I am now inserting the cookie into a hidden form field and submit it like that, and then read that field on server side. – Beppe Apr 23 '18 at 14:01
0

Are you sure to set up cookie?

To store state, the origin server includes a Set-Cookie header in an HTTP response. In subsequent requests, the user agent returns a Cookie request header to the origin server.