使用 express 设置 cookie 后如何重定向 url?

How to redirect url after setting cookie using express?

这是我在 express router 中的登录码:

if (password === realpassword) {
    res.cookie('thecookie', 'somethingliketoken');
    res.redirect(302, '/somepages');
} else {
    res.status(403).end();
}

我想设置 cookie 以便 /somepages 可以识别这个用户是谁。

但是我得到了错误Error: Can't set headers after they are sent.

我已经试过了return res.redirect(302, '/somepages');。对 /somepages 的查询已正确发送,但该页面仍保留在我的 /login.

请帮忙。

我想我明白了。 我使用 AJAX 发布了用户名和密码,因此 302 重定向被发送到 AJAX 查询,是的,它重定向成功但 它是针对 AJAX 查询,不是针对页面,这就是收到第二个查询但页面没有改变的原因。

          this.$http({
                url: '/userLogin',
                method: 'post',
                data: {
                    username: this.username,
                    password: SHA3(this.password, {outputLength: 256}).toString(),
                },
            }).then(res => {
                console.log(res);
                this.hintColor = '#00bdd8';
                this.hint = 'success';
            }).catch(err => {
                this.hintColor = 'red';
                if (err.response.status == 403) {
                    this.hint = 'mismatch';
                } else {
                    this.hint = '500err';
                }
            });

我觉得可能不应该这样用

将改用 window.location

如果还有其他方法,非常感谢您的帮助。

我在登录 post 请求中做了类似的事情,它对我有用。

app.post('/index',function(req,res){
  var uname = req.body.Username;
  var pwd = req.body.Password;
  if(uname && pwd === 'admin'){
    var token = jwt.sign( { username: uname }, 'q1W2e3R4t5Y6u7I8o9P',{ expiresIn: '1m' }
      );
    res.cookie('auth',token);
    res.redirect('home');
    console.log('Authentication is done successfully.....');
    console.log(token);
  }
});