首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fetch:从fetch响应中获取cookies

fetch:从fetch响应中获取cookies
EN

Stack Overflow用户
提问于 2016-08-28 13:50:20
回答 3查看 38.8K关注 0票数 14

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

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

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

这是我的代码:

代码语言:javascript
复制
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没有设置cookies,在应用程序Cookies -> localhost:8080中:“网站没有cookies”。

你知道怎么让它工作吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-08-30 14:28:44

问题原来是未设置fetch选项credentials: same-origin/include。因为fetch文档提到了在请求时发送cookie所需的这个选项,所以在读取cookie时没有提到这一点。

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

代码语言:javascript
复制
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 });
      }
    });
票数 9
EN

Stack Overflow用户

发布于 2020-05-06 13:19:50

来自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_APIDifference与jQuery部分

  • fetch() 不会接收跨站点cookies。您不能使用fetch()建立跨站点会话。Set-来自其他站点的Cookie标头被默认忽略。
  • fetch() 不会发送cookies凭证,除非您设置了 init选项。2017年8月25日起:规范将默认凭证策略改为同源。火狐自61.0b13起发生了变化。)
票数 3
EN

Stack Overflow用户

发布于 2019-06-08 12:00:43

我花了很长时间,但没有一个对我有效。

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

希望它也能为你工作。

代码语言:javascript
复制
{
  method: "POST",
  headers: {
    "content-type": "API-Key",
  },
  credentials: "include",
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39188376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档