我有一个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请求.
编辑:
这是登录的端点函数(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) .您还可以将基本网址指定为${window.location.origin} / api或/ api.
