尝试使用react和fetch发送cookie

adr*_*nay 12 cookies fetch reactjs

我一直试图在我的应用程序中实现一些身份验证组件几个小时,我仍然不理解正在发生的一些事情.

基本上,我想发送一个POST request包含一些credentials我的API,cookie如果凭证有效,它会给我一个带有令牌的后面.然后,cookie应该包含在我API的所有未来请求的标题中(我认为这是自动的).

server.js(我的API现在是一个模型,带有JSON文件)

...
app.post('/api/login', jsonParser, (req, res) => {
  fs.readFile(ACCOUNTS_FILE, (err, data) => {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    const accounts = JSON.parse(data);
    const credentials = {
      email: req.body.email,
      password: req.body.password,
    };
    var token = null;

    for (var i = 0; i < accounts.length; ++i) {
      const account = accounts[i];

      if (account.email === credentials.email
      && account.password === credentials.password) {
        token = account.token;
        break;
      }
    }

    if (token) {
      res.setHeader('Set-Cookie', `access_token=${token}; Secure; HttpOnly;`);
      res.json({ token });
    } else {
      res.json({ token: null });
    }
  });
});
...
Run Code Online (Sandbox Code Playgroud)

app.js

...
handleConnection(e) {
    e.preventDefault();

    const email = this.state.email.trim();
    const password = this.state.password.trim();
    if (!email && !password) {
      return (false);
    }

    fetch(loginUrl, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        credentials: 'include',
      },
      body: JSON.stringify(this.state),
    })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.warn(error);
    });

    return (true);
  }
...
Run Code Online (Sandbox Code Playgroud)

现在console.log(data)总是显示我的令牌(如果我的凭据错误,则为null),但cookie不起作用...

https://gyazo.com/170e580f879a9b0b87a8435acdf60a36

看,我收到Set-Cookie标题,但我的页面上仍然没有cookie.

即使我设法获取cookie,当我尝试使用document.cookie = "access_token=123";然后再次发送请求时,我的cookie不会像使用jQuery Ajaxcall一样进入我的标头:

https://gyazo.com/bd9c4533da15de7b8742be269f689b9b

在这里读到,添加credentials: 'include'会节省一天,但遗憾的是它没有.

我在这里错过了什么?

提前致谢!

小智 12

我遇到了同样的问题,我在Peter Bengtsson的评论中找到了答案:https://davidwalsh.name/fetch

如果我理解,在你的情况下,获取应该是:

fetch(loginUrl, {
  credentials: 'same-origin',
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(this.state),
})
Run Code Online (Sandbox Code Playgroud)

  • @阿莱西奥·桑塔克罗切。如何获取cookie值? (2认同)