【问题标题】:How to read cookies on server-side with Express?如何使用 Express 在服务器端读取 cookie?
【发布时间】:2017-10-18 11:21:41
【问题描述】:

在我的客户端,我在用户的 cookie 中保存了一个令牌:

this.socket.on('server:authentication', function(tokenObject){
  if(tokenObject){
    sessionStorage.setItem("token", tokenObject);
    this.setState({ submitted: true});
  }
}.bind(this));

然后我想在服务器端读取该令牌,但是当我这样做时:

app.use(cookieParser());

app.use(function(req, res, next){
    const { token } = req.cookies;
    console.log(token);
...
});

我在控制台上得到“未定义”。当我尝试console.log(req.cookies.token) 时也是如此。我怎样才能做到这一点?

【问题讨论】:

  • 您是否将所需的 cookie 附加到 HTTP 请求?当您致电 req.cookies 时,您正在检查附加到该请求的 cookie。仅仅因为 cookie 已在客户端设置,并不意味着它们会自动附加到您的 HTTP 请求中。
  • 不,我没有附加我坚持的 cookie 它是自动制作的。如何让客户端发送他的 cookie?
  • 这取决于您用来发出请求的内容,但我猜您可能需要将 withCredentials 设置为 true。例如,here's how to do it with jQuery

标签: node.js express


【解决方案1】:

您需要在客户端代码中设置 cookie,您当前设置的是 sessionStorage,这是一个不同的野兽。

this.socket.on('server:authentication', function(tokenObject){
    if(tokenObject){
        document.cookie = 'token=' + tokenObject;
        sessionStorage.setItem("token", tokenObject);
        this.setState({ submitted: true});
    }
}.bind(this));

How to set cookie and get cookie with JavaScript

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2016-05-29
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多