即使使用代理,Nodejs 也不会为 React CRA 应用程序设置 cookie

2023-12-22

我有一个nodejs/express + React CRA 应用程序,我正在尝试从nodejs 设置一个cookie。服务器位于端口 4001,因此在我的 React 应用程序的 project.json 中我有"proxy": "http://localhost:4001"设置,但 cookie 仍然不会在浏览器中设置。

我也在生产模式下对其进行了测试,React 应用程序直接从 Nodejs 提供服务,并且一切正常。

这是我设置 cookie 的方法。我在这里尝试了几种不同的选项组合,它们都有相同的结果。

res.cookie('jwt', token, {
    httpOnly: false,
    sameSite: false,
    signed: false,
    secure: false,
    encode: String
});
res.header('Access-Control-Allow-Credentials', 'true');

编辑:在客户端,我使用 Axios 来处理我的 ajax 请求。

Edit:

这是登录的端点函数(POST /api/users/login):

login: function(req, res) {
    User.findOne({
        $or: [{email: req.body.username}, {username: req.body.username}]
    }).exec().then(user => {
        if(user) {
            if(user.checkPassword(req.body.password)) {
                jwt.sign({ userID: user._id }, 'secret', (err, token) => {
                    res.cookie('jwt', token, {
                        httpOnly: false,
                        sameSite: false,
                        signed: false,
                        secure: false,
                        encode: String
                    });
                    res.header('Access-Control-Allow-Credentials', 'true');
                    res.status(200).send({ status: 'ok', message: 'Success'});
                });
            }
            else {
                return res.status(401).send({ status: 'error', message: 'Invalid username/password combination. Please try again.' });
            }
        }
        else {
            return res.status(401).send({ status: 'error', message: 'Invalid username/password combination. Please try again.' });
        }
    }, err => {
        return res.status(500).send({ status: 'error', message: 'unexpected error' });
    });
}

这是客户端登录代码:

login(username, password) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: 'http://localhost:4001/api/users/login',
            data: {
                username,
                password
            }
        }).then((res) => {
            resolve(res.data);
        }, (err) => {
            reject(err);
        });
    });
}

服务器位于端口 4001,React CRA 服务器位于 3000


为了允许浏览器设置 cookie 并遵守同源策略,您的客户端代码应该查询http://localhost:3000/api/users/login(与客户端相同的主机)而不是(代理)服务器 URL(端口 4001)。

您还可以将基本 url 指定为${window.location.origin}/api要不就/api.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使使用代理,Nodejs 也不会为 React CRA 应用程序设置 cookie 的相关文章

随机推荐