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

问题描述

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

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

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

...app.post('/api/login', jsonParser, (req, res) => {fs.readFile(ACCOUNTS_FILE, (err, data) => {如果(错误){控制台.错误(错误);process.exit(1);}常量帐户 = JSON.parse(data);常量凭据 = {电子邮件:req.body.email,密码:req.body.password,};var令牌=空;for (var i = 0; i 

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

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

我在 here 中阅读了添加 credentials: 'include' 可以挽救这一天,但不幸的是它没有.

我在这里错过了什么?

提前致谢!

解决方案

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

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

fetch(loginUrl, {凭据:'同源',方法:'POST',标题:{接受:'应用程序/json',内容类型":应用程序/json"},正文:JSON.stringify(this.state),})

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.

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 (my API is a mockup for now, with JSON files)

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

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

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

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 :

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

What am I missing here?

Thanks in advance!

解决方案

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:32