Use express-session in CORS?

Project (client): https://mcve.glitch.me
Project (server): https://serve-mcve.glitch.me

I’m trying to use express-session to store session cookies on server side. But, for some reasons, the cookies aren’t stored. I’ve learnt express-session from glitchypastepen project. And, there it works, IMO.

You can see console is logging:

text: tree
session text (init): tree
session text (final): undefined

The above project is a sample of a big upcoming project :wink:
Is this problem happening due to a cross-origin request? or are there any other reasons?


Edit page (server): https://glitch.com/edit/#!/serve-mcve
(logs have been mentioned in there)

1 Like

For the lazy people among us, could you paste the lines of code that produces the console output?

2 Likes

@vrintle here is a fix!

  1. go to package.json, and install the package “cors”
  2. Go to the file with the server data, and put in the following line of code at the top: var cors = require("cors")
  3. Go to where you initialize your express app ( Where you see var app = express() and go one line down
  4. put the following code on that line: app.use(cors())

That will fix cors being a pain in the butt, and actually let requests and such through.

please lmk if this fixed your issue

@Jonyk56 No, actually it would work if I hadn’t been storing cookies, and doing just GET and POST requests.

Reason: the cors library wouldn’t work here as in cors, they probably do:

resp.header('Access-Control-Allow-Origin', '*');
resp.header('Access-Control-Allow-Headers', '*');

which would fail if I’m storing cookies!

On MDN, I got the exact solution, which I’m sharing now,

resp.header('Access-Control-Allow-Credentials', true);
resp.header('Access-Control-Allow-Origin', 'https://mcve.glitch.me'); // only_one_url_here');
resp.header('Access-Control-Allow-Headers', 'Content-Type, POST, GET, OPTIONS, DELETE');

And, while doing fetch on client-side, add credentials: "include" like,

fetch('https://serve-mcve.glitch.me/add', {
    ...
    credentials: 'include',
    ...
})

they both should work…?

@Jonyk56 see this post on stackoverflow. It is the post which solved my issue

2 Likes