node.js - transfer cookies on a server/server request -
in universal app, loose every users cookies on server/server http request. have build small nodejs app reproduce thing:
const fetch = require('isomorphic-fetch'); const bodyparser = require('body-parser'); const cookieparser = require('cookie-parser'); const session = require('express-session'); const server = require('express')(); server.use(bodyparser()); server.use(cookieparser()); server.use(session({ secret: 'foo', httponly: false })); server.get('/set-cookies', (req, res) => { req.session.user = { name: 'john doe' }; res.send('ok'); }); server.get('/a', (req, res) => { console.log('cookie in = ', req.cookies); // cookies here ! const options = { credentials: 'include' }; fetch('http://localhost:3131/b', options) .then( () => { res.send('ok'); }); }); server.get('/b', (req, res) => { console.log('cookies in b = ', req.cookies); // cookies lost ! how ? res.sendstatus(200); }); server.listen(3131);
1) hit /set-cookies 2) hit /a (the cookies here expected)
issue: when /a controller make ajax request /b, won't transfer cookies, the route /b unable authenticate user
how transfer users cookies on every requests ? have heard "cookie jar" couldn't explain is, , didn't find clean explanation on web, if share knowledges that, great !
whatwg-fetch
has option send cookies following, doesn't seem work.
fetch('http://localhost:3131/b', { credentials: 'same-origin' });
you can send manually cookie fetch
following way.
server.get('/a', (req, res) => { console.log('cookie in = ', req.cookies); // cookies here ! const options = { 'headers' : { 'cookie': req.headers.cookie } }; fetch('http://localhost:3131/b', options) .then( () => { res.send('ok'); }); });
Comments
Post a Comment