【问题标题】:Node Express setting cookiesNode Express 设置 cookie
【发布时间】:2018-03-18 00:17:37
【问题描述】:

这里可能有误会。

我有一个在 localhost:3000 运行的节点服务器,以及一个在 localhost:8080 运行的 React 应用程序。

React 应用程序正在向节点服务器发出 get 请求 - 我的服务器代码如下所示:

const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const express = require('express');

const app = express();

app.use(cookieParser());

app.get('/', function (req, res) {
    let user_token = req.cookies['house_user']; // always empty

    if (user_token) {
        // if the token exists, great!
    } else {
        crypto.randomBytes(24, function(err, buffer) {
            let token = buffer.toString('hex');
            res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
            res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: false });
            res.send(token);
        });
    }
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

我正在尝试设置house_user 令牌,以便以后可以跟踪来自用户的请求。

但是,没有在用户上设置令牌(来自localhost:8080 的请求)-house_user 令牌始终为空(实际上,req.cookies 完全为空)。我需要做其他事情吗?

【问题讨论】:

  • res.cookie...() 是您只需删除res.append()。 secure:true 将允许 cookie 仅适用于 https。请求是否在 https 上运行?
  • @jfriend00 你是对的——我的错;过多筛选 Stack 帖子并尝试多种解决方案 :')

标签: node.js reactjs express


【解决方案1】:

我刚刚尝试了下面的代码(并且成功了)。提醒一下,您可以将其粘贴到 myNodeTest.js 中,然后运行 ​​node myNodeTest.js 并访问 http://localhost:3003。如果它确实有效,则可能意味着您遇到了 CORS 问题。

[EDIT] withCredentials:true 应该使用 axios 来解决问题。

axios.get('localhost:3000', {withCredentials: true}).then(function (res) { console.log(res) })
const express = require('express')
const cookieParser = require('cookie-parser')
const crypto = require('crypto');

const port = 3003

app.use(cookieParser());

app.get('/', function (req, res) {
    let user_token = req.cookies['house_user']; // always empty

    if (user_token) {
        // if the token exists, great!
    } else {
        crypto.randomBytes(24, function(err, buffer) {
            let token = buffer.toString('hex');
            res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
            res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: true });
            res.append('Set-Cookie', 'house_user=' + token + ';');
            res.send(token);
        });
    }
});

app.get('/', (request, response) => {
  response.send('Hello from Express!')
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

【讨论】:

  • 嘿 :) - 我需要 cookie-parser(更新了我的帖子以现在显示) - 不幸的是,在后续请求中我仍然没有收到来自 req.cookies 的 cookie。
  • 您是否尝试过我发布的代码,仅使用简单的node myNodeTest.js 并访问了 localhost:3003?我得到了你的饼干 ;)
  • 这是我认为我可能误解的地方 - 我的目标是在客户端上设置 cookie(即我的 React 应用程序在 localhost:8080 上运行),它正在向 Node 服务器发出 get 请求.我不确定这是否可能。
  • 当然,我知道,但如果它像我提到的那样工作,我们会更进一步知道它可能与 CORS 有关。你在使用 Next.js 之类的 SSR 吗?
  • @ConnorCartwright 不客气,在你告诉我关于 Axios 的事情后,我确信问题出在那儿 ;) 干杯
【解决方案2】:

将我的评论变成答案,因为它似乎已经解决了您的问题。

由于您在 http 而不是 https 上运行,因此您需要从 cookie 中删除 secure: true,因为这将使 cookie 仅通过 https 连接发送,这将阻止浏览器发送它通过您的http 连接返回给您。

另外,删除res.append(...),因为只需res.cookie()。

【讨论】:

  • 在 Asten 的回答中回复 cmets,问题仍然存在,但可能只是我试图做一些不可能的事情。
  • @ConnorCartwright - 您的 axios 请求应该是:axios.get('http://localhost:3000').then(...).catch(...),并带有 URL 中的协议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2016-08-17
  • 2021-11-18
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多