我在带有superagent的API上发出POST请求,这基本上是一个登录api,用于对令牌进行签名并设置cookie。
从react发出请求的代码如下
agent
.post('http://localhost:3010/api/auth/login')
.send({username:this.state.username,password:this.state.password})
.end((err,res)=>{
if(err) console.log(err);
if(res.body.auth===true){
alert("Successful Login , You'll be Redirected");
history.push('/dashboard');
}
});在我的express服务器中,我使用了以下代码:
router.post('/login', function(req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
if (err) return res.status(500).send('Error on the server.');
if (!user) return res.status(404).send('No user found.');
var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
var token = jwt.sign({ id: user._id, role : user.role }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
res.cookie('auth',token);
res.status(200).send({ auth: true, token: token });
});
});我在响应中设置了cookie,但问题是从来没有在浏览器中设置cookie。这个问题不是我在使用POSTMAN检查APIS时出现的,而是在真正的浏览器中使用react中的apis时出现的问题。
我哪里错了?或者我还应该使用什么方法来获得结果
发布于 2018-01-13 02:29:26
我相信您正在将令牌作为可通过响应对象上的cookie属性访问的请求的一部分发送回客户端。不将cookie存储在浏览器cookie jar中。为此,您需要在superagent响应回调中查找cookie,然后使用localstorage客户端保存cookie。
https://stackoverflow.com/questions/48232038
复制相似问题