I have problem with setting a cookies via express. I'm using Este.js dev stack
and I try to set a cookie in API auth /login
route. Here is the code that I use in /api/v1/auth/login
route
res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999)});
res.status(200).send({user, token: jwt.token});
In src/server/main.js
I have registered cookie-parser
as first middleware
app.use(cookieParser());
The response header for /api/v1/auth/login
route contains
Set-Cookie:token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ..
but the cookie isn't saved in browser (document.cookie
is empty, also Resources - Cookies
tab in develepoers tools is empty) :(
EDIT:
I'm found that when I call this in /api/v1/auth/login
(without call res.send
or res.json
)
res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false});
next();
then the cookie is set AND response header has set X-Powered-By:Este.js
... this sets esteMiddleware
in expres frontend rendering part.
When I use res.send
res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}).send({user, token: jwt.token});`
next();
then I get error Can't set headers after they are sent.
because send
method is used, so frontend render throw this error.
But I have to send a data from API, so how I can deal with this?
Can some help me please? Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…