7

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? :)

4

1 回答 1

3

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.

于 2013-09-11T19:15:01.993 回答