简体   繁体   中英

How to share cookies across ports/domains with Express

I have two node.js (express) apps running on two different ports. One is running on localhost:3000 and the other is running at localhost:4000 . The app on port 3000 has the following cookie configuration:

app.use(express.cookieParser())

app.use(express.session({
    key: settings.session.key,
    secret: settings.session.secret,
    cookie: settings.session.cookie,
    fingerprint: function () { return '' },
    store: new MemoryStore()
}))

And the other app (on port 4000 ) has:

app.use(express.cookieParser())

app.use(express.session({
    key: settings.session.key,
    secret: settings.session.secret,
    cookie: settings.session.cookie,
    fingerprint: function() { return ''  },
    store: new MongoSessionStore({ db: db })
}))

They are both using the same session configuration object (only difference is one is being stored in MongoDB while the other is in-memory.

I set a cookie like so on localhost:3000 :

res.cookie('mycookie', 'bar', { domain: 'localhost:4000' })

And I then POST (with jquery.ajax) to a route on localhost:4000 , and the cookie mycookie is not present.

Note: I have CORS setup on localhost:4000 to accept the origin localhost:3000 , and when I post with Jquery I use xhrFields: { withCredentials: true } .

So my question is, how to configure the apps correctly to set cookies to one another? :)

I suggest that you share your session store between both apps.

Edit: Just to clarify you can't set cookies from one domain to another. So domainA can't set a cookie for domainB - you must get domainB to set the cookie (eg. by visiting domainB ). Using your current config you should be able to read the cookies as expected.

Originally, I thought you wanted to share state between two apps via cookies which is why I suggested sharing the session store between the apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM