尝试使用react和fetch获取然后发送cookie [英] Trying to get then send a cookie using react and fetch

查看:465
本文介绍了尝试使用react和fetch获取然后发送cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to implement some authentication component in my app for a few hours now, and I still don't understand some of the things that are happening.

基本上,我想向我的发送一个 POST请求包含一些凭证 API ,如果凭据有效,它会向我发送一个 cookie 和一个令牌。然后,该cookie应该包含在我的API的所有将来请求的标头中(我认为这是自动的)。

Basically, I'd like to send a POST request containing some credentials to my API, which sends me a cookie back with a token if the credentials worked. Then, the cookie should be included in the headers of all future requests to my API (which I believed was automatic).

server.js(我的API是

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

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

Now the console.log(data) always displays my token (or null if my credentials are wrong), but the cookie thing doesn't work...

看,我收到了 Set-Cookie 标头,但是我

See, I receive the Set-Cookie header, but I still have no cookie on my page.

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

And even if I managed to get the cookie, when I try to create a cookie using document.cookie = "access_token=123"; and then send the request again, my cookie doesn't go in my header like it would with a jQuery Ajaxcall :

我阅读了此处,添加凭据: include 可以节省一天的时间,但不幸的是没有。

I read here that adding credentials: 'include' would save the day, but unfortunately it didn't.

我在这里想念什么?

预先感谢!

推荐答案

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

I had the same problem and I found the answer in Peter Bengtsson's comment here: https://davidwalsh.name/fetch

如果我理解您的情况,则应为:

If I understood, in your case the fetch should be:

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

这篇关于尝试使用react和fetch获取然后发送cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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