CrazySynthax
CrazySynthax

Reputation: 15064

Node.js express: why can't I read cookies ?

I wrote a very simple node.js server:

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

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

app.get('/', function(req, res){
    res.sendFile(__dirname + "/hello.html");
});

app.get('/ajax', function(req, res) {
    console.log('ajax request received');
    console.log(req.cookies["username"])
})
app.listen(3000);

and a very simple client side html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1> Hello World </h1>
    <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <script>
        document.cookie = "username=John Doe";
        $.ajax({
            url: "http://127.0.0.1:3000/ajax",
        }).done(function() {
            alert('AJAX sent');
        });
    </script>
</body>
</html>

As you can understand, once the server runs and an end-user sends a get request to localhost:3000, the file 'hello.html' is served to client. The browser saves the cookie "username=John Doe" and sends AJAX request to endpoint localhost:3000/ajax. My intention is to read the content of the cookie in the server (I know that cookies are sent automatically from the client). However, req.cookies["username"] returns undefined.

Do you know why?

Upvotes: 2

Views: 2820

Answers (1)

CrazySynthax
CrazySynthax

Reputation: 15064

The problem is that I send a GET request to localhost:3000 and therefore the cookie is saved in the domain http://localhost. However, when I send an AJAX call to 127.0.0.1, the cookie is not sent because the browser treats 127.0.0.1 and localhost as different domains. Therefore, opening the browser with 127.0.0.1:3000 (instead of localhost:3000) can solve it.

Upvotes: 3

Related Questions