Node.js Express API在部署其Docker镜像后不发送标头。

huangapple go评论69阅读模式
英文:

Node.js Express API doesn't send headers if its docker image is deployed

问题

I've built a Node.js Express API, and when the user makes a successful (POST) /login request, the API sets the Authorization Token as a cookie in the browser. This works when running the Docker image locally, but when deployed on Azure and DigitalOcean, the cookie isn't set in the browser when using the React App. Postman and Insomnia work as expected with the deployed API. The CORS options in the API are set to allow all origins ("*").

英文:

I've built an Node.js Express API where whenever the user uses the (POST) /login, if logged successfully, the api will set the Authorization Token such as this:

  @Post('/login')
  @UseBefore(validationMiddleware(LoginUserDto, 'body'))
  async logIn(@Res() res: Response, @Body() userData: LoginUserDto) {
    const { cookie, user } = await this.authService.login(userData);
    res.setHeader('Set-Cookie', [cookie]);
    return user
  }

Whenever I run the docker image locally, if it was requested by a React app it would create the token as a cookie in the browser successfully.

Since it was working, I deployed in docker image of the API in Azure and Digitalocean (in order to see if would work on both. But when I tried to login with the deployed API, it would POST with success but the cookie wouldn't be set in the browser when using the React App (in the app the credentials were set to true in order to save).

I tried to call the deployed API with Postman and Insomnia and both would save the cookie from the successful login.

With this last experiment I was really confused because the API works as expected both in postman and in the react app when run locally, but when deployed only works as expected in postman and not in React. I can't understand if the problem is from react or from the API.

I have also tried using RTK and Axios in react and both got the same results.
In the CORS options from the API the origin is set to "*"

答案1

得分: 0

已经找到了,似乎在创建cookie时我没有设置Same-Site属性,默认是Lax,这不允许浏览器保存cookie。我将其设置为None,并且需要在其后加上secure

public createCookie(tokenData: TokenData): string {
    return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn}; SameSite=None; Secure`;
}
英文:

Already found out, seems like when creating the cookie I was not setting the Same-Site property and by default was Lax, which didn't let the browser save the cookie. I set it to none and needed to put secure after it.

public createCookie(tokenData: TokenData): string {
    return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn}; SameSite=None; Secure`;
  }

huangapple
  • 本文由 发表于 2023年1月3日 22:36:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/74994800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定