Node Express设置cookies

5

我可能理解有误。

我有一个运行在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 请求)上-实际上req.cookies完全为空,house_user令牌始终为空。我需要做其他事情吗?

1
你只需要使用 res.cookie...(),所以请移除 res.append()。设置 secure:true 将使 cookie 只在 https 下工作。请求是否在 https 上运行? - jfriend00
1
@jfriend00 你是对的 - 我错了;太多在 Stack 帖子中筛选并尝试多种解决方案 :') - Connor Cartwright
2个回答

4

我刚试过下面的代码(它可以工作)。提醒一下,你只需要将此代码粘贴到myNodeTest.js中,然后运行node myNodeTest.js并访问http://localhost:3003。如果它可以工作,那么很可能是因为你遇到了CORS问题。

[编辑] 使用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}`)
})

你试过我发布的代码了吗?只需要简单地运行 node myNodeTest.js 并访问 localhost:3003 就可以了。我得到了你的 cookie ;) - aquiseb
我不这么认为 - 我正在使用React和Axiom发出请求,例如:axios.get('http://localhost:3000').then(function (res) { console.log(res) }) - Connor Cartwright
我将根据您的反馈逐步进行编辑。问题确实来源于Axios,我有99%的把握。 - aquiseb
Asten - 添加 withCredentials: true 工作了!非常感谢你 :D - Connor Cartwright
1
@ConnorCartwright 不用谢,你告诉我关于 Axios 后,我就确定问题出在那里了 ;) 干杯 - aquiseb
显示剩余3条评论

1
由于我的评论似乎解决了你的问题,所以我将它转化为答案。
由于您正在运行 http 而不是 https ,因此您需要从cookie中删除 secure:true ,因为这将使cookie仅通过 https 连接发送,这将阻止浏览器通过 http 连接将其发送回您。
此外,请删除 res.append(...),因为只需要 res.cookie()

关于Asten答案的评论,问题仍然存在,但可能只是我试图做一些不可能的事情。 - Connor Cartwright
@ConnorCartwright - 你的axios请求应该是:axios.get('http://localhost:3000').then(...).catch(...),URL中应包含协议。 - jfriend00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接