fetch:从 fetch 响应中获取 cookie

fetch: Getting cookies from fetch response

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

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

我知道 passport 可以使用 flash 消息发回消息,但是 flash 需要会话,我想避免它们。

这是我的代码:

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 的开发工具上看到的那样:

但是 chrome 没有设置 cookie,在应用程序 -> Cookies -> localhost:8080: "The site has no cookies".

知道如何让它发挥作用吗?

问题出在未设置获取选项 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 });
      }
    });

我花了很长时间,但没有任何效果。

在网上尝试了几种解决方案后,这个对我有用。

希望它对你也有用。

{
  method: "POST",
  headers: {
    "content-type": "API-Key",
  },
  credentials: "include",
}

来自 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

的 jQuery 部分的差异
  • fetch() 不会收到 cross-site cookies。 你不能建立交叉 站点 session 使用 fetch()。 Set-Cookie headers 来自其他站点 默默无视。
  • fetch() 不会发送 cookie,除非您设置 凭据初始化选项。 自 2017 年 8 月 25 日起:规范更改了 默认凭证策略为 same-origin。 Firefox 改变了 61.0b13.)