【发布时间】:2018-06-22 06:10:02
【问题描述】:
我正在使用 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');
}
});
在我的快递服务器中,我正在使用此代码:
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 的 API 时出现的问题。
我哪里错了?或者我应该使用什么其他方法来获得结果
【问题讨论】:
-
你解决了吗?
标签: node.js reactjs express cookies superagent