Search code examples
node.jsexpresssession-cookies

Why are my cookies and signedCookies empty in req when I try to get them from port 3000?


I have an issue when I want to retrieve a session cookie from a get request with express.

My server is running on the port 8000 while my app is running on the port 3000.

When I directly go on http://localhost:8000/setcookie and /getcookie, I can get and set the cookies and it works fine. On another hand, when I try the same thing from http://localhost:3000 and use axios to get or post requests on the port 8000, the cookies and signedCookies are empty in the req and I don't know why. Is it because I send it from the port 3000 even though I'm listening and sending requests to the port 8000?

I tried with both get and post method to create a cookie. Neither of them seemed to work. I'm a bit lost.

I hope my explanation was clear enough, thanks a lot!

Server

const app = express()
const port = process.env.PORT || 8000
app.set("port", port)

const http = require('http').Server(app);

//Body Parser
var urlencodedParser = bodyParser.urlencoded({
    extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json());

//Définition des CORS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(cookieParser("secret")); 

app.get('/setcookie', function (req, res, next) {
  // Update views
  console.log("connection", req);
  var mail = req.body.email
  res.cookie('b', 'jefaisuntest', {signed: true, expire : 600000});

  // Write response
  res.send("cookie sent")
})

app.get('/getcookie', function(req, res) {
    var username = req.signedCookies['b'];

    console.log("iciiii", req)
    if (username) {
        return res.send(username);
    }

    return res.send('No cookie found');
});

const server = http.listen(port, function () {
    console.log(`listening on *:${port}`)
})

Client

import axios from 'axios';

const headers = {
    'Content-Type': 'application/json'
}
const burl = "http://localhost:8000"

export default {
    login : function(email:string, password:string) {
        axios.get(burl + '/setcookie')
    },
    isAuth : function() {
        axios.get(burl + '/getcookie')
    },
}

Solution

  • What @mnesarco said is correct - you are technically running two different servers, which means that any requests you send between the two are CORS requests. In order to share send cookies in a CORS request, you need to set the withCredentials flag to true:

    export default {
        login : function(email:string, password:string) {
            axios.get(burl + '/setcookie', { withCredentials: true })
        },
        isAuth : function() {
            axios.get(burl + '/getcookie', { withCredentials: true })
        },
    }
    

    See this answer from a similar situation or this mdn page for more information.