fetch:从 fetch 响应中获取 cookie [英] fetch: Getting cookies from fetch response

查看:204
本文介绍了fetch:从 fetch 响应中获取 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to implement client login using fetch on react.

我正在使用护照进行身份验证.我使用 fetch 而不是常规 form.submit() 的原因是因为我希望能够从我的 express 服务器接收错误消息,例如:用户名或密码错误".

I'm using passport for authentication. The reason I'm using fetch and not regular form.submit(), is because I want to be able to recieve error messages from my express server, like: "username or password is wrong".

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

I know that passport can send back messages using flash messages, but flash requires sessions and I would like to avoid them.

这是我的代码:

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

The server sends the cookies just fine, as you can see on chrome's dev tools:

但是chrome没有设置cookies,在Application -> Cookies -> localhost:8080: "The site has no cookies".

But chrome doesn't set the cookies, in Application -> Cookies -> localhost:8080: "The site has no cookies".

知道如何让它工作吗?

推荐答案

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

The problem turned out to be with the fetch option credentials: same-origin/include not being set. As the fetch documentation mentions this option to be required for sending cookies on the request, it failed to mention this when reading a cookie.

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

So I just changed my code to be like this:

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 });
      }
    });

这篇关于fetch:从 fetch 响应中获取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆