简体   繁体   English

HttpOnly cookie 仅在第二次请求后设置

[英]HttpOnly cookie is set only after the second request

I have a server (Node.js + Nest.js) and a client (Angular 11).我有一个服务器(Node.js + Nest.js)和一个客户端(Angular 11)。

The client submits a login request and the server logs in the user and sets a HttpOnly cookie in the response.客户端提交登录请求,服务器登录用户并在响应中设置HttpOnly cookie。
The wierd thing is that the cookie is set in the browser only after submitting 2 requests , then it works fine (If i use postman for example, it saves the cookie with no problems).奇怪的是,cookie仅在提交 2 个请求后才在浏览器中设置,然后它工作正常(例如,如果我使用 postman,它会毫无问题地保存 cookie)。 I can see in each response (even the first one) the cookie set in the headers.我可以在每个响应(甚至是第一个响应)中看到标题中设置的 cookie。

client code:客户端代码:

this.http.post<LoginResponse>(`server_path/login`, {
      email: 'example@gmail.com',
      password: '12345678',
      rememberMe: false
}).subscribe(_ => console.log('Logged in!'), _ => console.log('wrong credentials'))

server code:服务器代码:

const { result, error } = await this.authService.loginLocalUser(req.user, body.rememberMe)
if (error) throw new UnauthorizedException()

if (body.rememberMe) {
  const oneYearFromNow = new Date()
  oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1)
  res.cookie('refreshToken', result.refreshToken, { httpOnly: true, expires: oneYearFromNow })
} else
  res.cookie('refreshToken', result.refreshToken, { httpOnly: true })

return { accessToken: result.accessToken }

EDIT: even when the cookie is set (after the second time), I cant see it being sent in requests, even tho I use credentials: true on both client and server.编辑:即使设置了cookie(第二次之后),我也看不到它在请求中发送,即使我在客户端和服务器上都使用了credentials: true

In the end the thing that solved my problem was just clearing the browser cache, no idea why its like that (only in chrome), but now everything is working as expected.最后解决我的问题的事情只是清除浏览器缓存,不知道为什么会这样(仅在 chrome 中),但现在一切都按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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