【问题标题】:Cookie is Not Set - SuperagentCookie 未设置 - Superagent
【发布时间】: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


【解决方案1】:

我相信您将令牌作为可通过响应对象上的 cookie 属性访问的请求的一部分发送回客户端。不将 cookie 存储在浏览器 cookie jar 中。为此,您需要在超级代理响应回调中查找 cookie,然后使用 localstorage 客户端保存 cookie。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2021-10-21
    • 2012-02-11
    • 2016-02-12
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多