【问题标题】:Trying to get then send a cookie using react and fetch尝试使用 react 和 fetch 获取然后发送 cookie
【发布时间】:2016-08-22 04:42:44
【问题描述】:

我已经尝试在我的应用中实现一些身份验证组件几个小时了,但我仍然不明白正在发生的一些事情。

基本上,我想向我的API 发送一个包含一些credentialsPOST request,如果凭据有效,它会向我发送一个带有令牌的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 });
    }
  });
});
...

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

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

看,我收到了 Set-Cookie 标头,但我的页面上仍然没有 cookie。

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

我读到 here 说添加 credentials: 'include' 可以节省时间,但不幸的是它没有。

我在这里错过了什么?

提前致谢!

【问题讨论】:

    标签: cookies reactjs fetch


    【解决方案1】:

    我遇到了同样的问题,我在 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),
    })
    

    【讨论】:

    • 是的,凭据:'same-origin' 效果很好。感谢分享此代码。
    • @Alessio Santacroce。如何访问 cookie 值??
    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2019-01-27
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多