Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cookie fails in ExpressJs

I have a problem in Express 4.x.I can't set any cookies. I want to set a cookie via Ajax request, i do the request, my server-side res.cookie() is executed, in my response headers i can find my 'set-cookie' header with the specific name and value, but nothing happens, the cookie is not registered. I have no HttpOnly or secure flag.

Cookie set example :

res.cookie('my_cookie','value',{maxAge:500,secure:false,httpOnly:false});

What i've noticed is that if i set maxAge 500 for example, my cookie expiration date from response headers is about 5 hours ago, so i tried to add a bigger value, but nothing happened.

It is like my set-cookie header is ignored. I don't use AngularJS, just jQuery.

If i put the set-cookie content in document.cookie from js console, the cookie is registered..

Thanks in advance and sorry for my bad english .

like image 540
Cozy Rin Avatar asked Oct 23 '25 12:10

Cozy Rin


1 Answers

Version 4.0 removed a lot of the convenience middleware from the library for a more modular architecture; in this case you need to reference the cookie-parser middleware. Without it req.cookies is just an empty {}.

$npm install cookie-parser

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

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

You also need it to sign cookies:

enter image description here

like image 169
adamrights Avatar answered Oct 26 '25 03:10

adamrights