express - fetch:从 fetch 响应中获取 cookie

标签 express cookies fetch

我正在尝试使用 fetch on react 来实现客户端登录。

我正在使用护照进行身份验证。我使用的原因 fetch而不是常规 form.submit() , 是因为我希望能够从我的快速服务器接收错误消息,例如:"username or password is wrong" .

我知道护照可以使用 flash 发回消息消息,但 flash需要 session ,我想避免它们。

这是我的代码:

fetch('/login/local', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password,
      }),
    }).then(res => {
      console.log(res.headers.get('set-cookie')); // undefined
      console.log(document.cookie); // nope
      return res.json();
    }).then(json => {
      if (json.success) {
        this.setState({ error: '' });
        this.context.router.push(json.redirect);
      }
      else {
        this.setState({ error: json.error });
      }
    });

服务器发送 cookie 就好了,正如您在 chrome 的开发工具上看到的那样:
Network - Cookies
Network - Headers

但是 chrome 没有设置 cookie,在 Application -> Cookies -> localhost:8080 中:“该站点没有 cookie”。

知道如何使它工作吗?

最佳答案

问题出在 fetch 选项 credentials: same-origin/include未设置。
由于 fetch 文档提到在请求上发送 cookie 需要此选项,因此在读取 cookie 时没有提到这一点。

所以我只是把我的代码改成这样:

fetch('/login/local', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin',
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password,
      }),
    }).then(res => {
      return res.json();
    }).then(json => {
      if (json.success) {
        this.setState({ error: '' });
        this.context.router.push(json.redirect);
      }
      else {
        this.setState({ error: json.error });
      }
    });

关于express - fetch:从 fetch 响应中获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188376/

相关文章:

mysql - 如何在Sequelize中从主模型同一级别的包含模型返回结果?

ios - 表删除操作删除单元格内容而不是单元格本身?

javascript - 为 loginid 使用持久性 cookie 的风险

javascript - 使用嵌套的 Promise 创建 Promise 队列

javascript - 循环时await 调用会并行执行吗?

javascript - 一个服务器文件中的多个 Node.js "Apps"坏习惯?

node.js - 由于使用 pug 和 Node 的 MIME 类型不匹配,资源被阻止

javascript - 在启动之前请求用户应用程序时出错

angularjs - $cookies 与 angularjs 1.4 到期日期

php - cookie 值中的逗号在 ZF2 中被双重解析