Express 不设置 cookie [英] Express doesn't set a cookie
问题描述
我在通过 express 设置 cookie 时遇到问题.我正在使用 Este.js dev stack
并尝试在 API auth /login
路由中设置 cookie.这是我在 /中使用的代码api/v1/auth/login
路由
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});
在 src/server/main.js
中,我注册了 cookie-parser
作为第一个中间件
In src/server/main.js
I have registered cookie-parser
as first middleware
app.use(cookieParser());
/api/v1/auth/login
路由的响应头包含
Set-Cookie:token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ..
但是 cookie 没有保存在浏览器中(document.cookie
是空的,develepoers 工具中的 Resources - Cookies
标签也是空的) :(
but the cookie isn't saved in browser (document.cookie
is empty, also Resources - Cookies
tab in develepoers tools is empty) :(
我发现当我在 /api/v1/auth/login
中调用它时(没有调用 res.send
或 res.json
)
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();
然后设置 cookie 并且响应头设置了 X-Powered-By:Este.js
... 这将 esteMiddleware
设置在表示前端渲染部分.
then the cookie is set AND response header has set X-Powered-By:Este.js
... this sets esteMiddleware
in expres frontend rendering part.
当我使用 res.send
res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}).send({user, token: jwt.token});`
next();
然后我得到错误发送后无法设置标题.
因为使用了send
方法,所以前端渲染会抛出这个错误.
then I get error Can't set headers after they are sent.
because send
method is used, so frontend render throw this error.
但是我必须从 API 发送数据,所以我该如何处理?
But I have to send a data from API, so how I can deal with this?
推荐答案
我遇到了同样的问题.服务器响应带有 cookie 集:
I had the same issue. The server response comes with cookie set:
Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT
但是浏览器没有保存cookie.
But the cookie was not saved by a browser.
我就是这样解决的.
我在客户端代码中使用 fetch
.如果您未在 fetch
选项中指定 credentials: 'include'
,则 cookie 既不会发送到服务器,也不会被浏览器保存,尽管服务器响应设置了 cookie.
I use fetch
in a client-side code. If you do not specify credentials: 'include'
in fetch
options, cookies are neither sent to server nor saved by a browser, although the server response sets cookies.
示例:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return fetch('/your/server_endpoint', {
method: 'POST',
mode: 'same-origin',
redirect: 'follow',
credentials: 'include', // Don't forget to specify this if you need cookies
headers: headers,
body: JSON.stringify({
first_name: 'John',
last_name: 'Doe'
})
})
这篇关于Express 不设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!