提取:从提取响应中获取Cookie

Ger*_*api 6 cookies fetch express

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

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

我知道护照可以使用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 });
      }
    });
Run Code Online (Sandbox Code Playgroud)

服务器发送的cookie很好,如您在chrome的dev工具上看到的: 网络-Cookies 网络-标头

但是chrome不会设置cookie,在“应用程序”->“ cookies”->“ localhost:8080”中:“该站点没有cookie”。

任何想法如何使其工作?

Ger*_*api 9

问题原来是credentials: same-origin/include没有设置fetch 选项。由于 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 });
      }
    });
Run Code Online (Sandbox Code Playgroud)

  • 这个答案实际上并没有显示如何从响应中获取 cookie 值,这是最初的问题。 (6认同)
  • 即使在设置了凭据之后,这对我也不起作用:'same-origin',/'include。 (3认同)
  • 我通过设置凭据解决了这个问题:'include' 并将标题“Access-Control-Allow-Origin”设置为“http://localhost:3000”(我的 Webstorm 正在从与我的 Express 服务器不同的服务器提供反应页面) )并将标题“Access-Control-Allow-Credentials”设置为“true” (3认同)

Kon*_*lin 8

来自Mozilla 上 Fetch API的与 jQuery部分的差异:

\n
    \n
  • fetch()不会接收跨站点 cookie。您可以使用 fetch()\xe2\x80\x99t 建立跨站点会话。来自其他站点的 Set-Cookie 标头将被\n忽略。
  • \n
  • 除非您设置\ncredentials 初始化选项,否则fetch()不会\xe2\x80\x99t 发送 cookies 。自 2017 年 8 月 25 日起:规范将\n默认凭据策略更改为同源。Firefox 自\n61.0b13 起发生了变化。)
  • \n
\n