简体   繁体   English

没有使用 Node + Express + Nginx 设置 Cookie

[英]Cookie not set with Node + Express + Nginx

I have a Node app using Express, and I try to set a cookie to my client.我有一个使用 Express 的 Node 应用程序,我尝试为我的客户端设置一个 cookie。 It works well on local environment (http).它在本地环境(http)上运行良好。 But once I put in production (https), I receive well the cookie (I can see it in the response), but it is not set.但是一旦我投入生产(https),我就会很好地收到cookie(我可以在响应中看到它),但它没有设置。 Any idea?任何想法?

Nginx conf: Nginx 配置:

http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 65;
  gzip on;

  server {
    listen 443 ssl default_server;
    listen [::]:443 default_server;
    server_name back.domain.com;

    ssl_certificate  /etc/letsencrypt/.../fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/.../privkey.pem;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
  }
}

Node app:节点应用:

const api = express()

api.enable('trust proxy')
api.use(cors({origin: 'https://front.domain.com', credentials: true}))

api.post('/login', (req, res) => {
  // validate credentials and generate token
  // set expires to 24h

  res
    .cookie('token', token, {expires, httpOnly: true, secure: true})
    .sendStatus(204)
})

Front:正面:

// I use the axios lib
axios({
  baseURL: 'https://back.domain.com',
  url: '/login',
  withCredentials: true,
  method: 'POST'
}

I figured out after hours of research... I had to set the domain key to domain.com when I create the cookie:经过数小时的研究后,我发现...在创建 cookie 时,我必须将domain密钥设置为domain.com

res
  .cookie('token', token, {expires, httpOnly: true, secure: true, domain: 'domain.com'})
  .sendStatus(204)

Another possible reason for cookies not being set is having option:未设置 cookie 的另一个可能原因是有选项:

secure: true

when protocol is http (not secure) instead of https .当协议是http (不安全)而不是https时。

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

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