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

chr*_*oes 7 express reactjs webpack-dev-server axios create-react-app

我有一个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');
Run Code Online (Sandbox Code Playgroud)

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

编辑:

这是登录的端点函数(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' });
    });
}
Run Code Online (Sandbox Code Playgroud)

这是客户端登录代码:

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);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

服务器在端口4001上,React CRA服务器在3000上

riw*_*iwu 5

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

您也可以将基本网址指定为${window.location.origin}/api/api