Express 获取:从获取响应获取cookie

Express 获取:从获取响应获取cookie,express,cookies,fetch,Express,Cookies,Fetch,我正在尝试使用fetch on react实现客户端登录 我用passport认证。我之所以使用fetch而不是常规的form.submit(),是因为我希望能够接收来自express服务器的错误消息,例如:“用户名或密码错误” 我知道passport可以使用flash消息发送回消息,但flash需要会话,我希望避免使用会话 这是我的代码: fetch('/login/local', { method: 'POST', headers: { Accept:

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

我用passport认证。我之所以使用
fetch
而不是常规的
form.submit()
,是因为我希望能够接收来自express服务器的错误消息,例如:
“用户名或密码错误”

我知道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没有设置cookies,在Application->cookies->localhost:8080:“站点没有cookies”


知道如何使其工作吗?

问题在于没有设置获取选项
凭证:相同来源/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",
}

From与jQuery的差异

  • fetch()将不会接收跨站点cookie。您无法建立跨站点cookie 使用fetch()的站点会话。来自其他站点的设置Cookie头是 默默地忽略
  • fetch()不会发送cookies,除非您设置了 凭证初始化选项。自2017年8月25日起:规范更改了 同一来源的默认凭据策略。Firefox自 61.0b13。)

您可以发布服务器端的代码吗?也许这有助于您发现问题,请参阅我的答案。谢谢,顺便说一句。这对我来说不起作用,即使在设置了凭据“同一来源”、/“包括”之后。即使凭据与同一来源相同,这也不起作用凭据“同一来源”是默认值,不是吗?无效凭据:“同一来源”或“包括”我通过设置凭据:“包括”并将标题“访问控制允许来源”设置为“”(我的Webstorm正在为来自不同于我的express服务器的react页面提供服务),以及将标题“访问控制允许凭据”设置为“true”来修复此问题