【问题标题】:How do I fix authentication not working when I send a request from react frontend but that works in backend?当我从反应前端发送请求但在后端有效时,如何修复身份验证不起作用?
【发布时间】:2022-10-20 17:06:48
【问题描述】:

所以我有这个与 localhost 上的 api 交互的应用程序,我正在使用 express、mongodb 并为前端做出反应。用于身份验证的护照本地身份验证。我有一个问题,当我在反应中使用 fetch api 时,身份验证不会持续存在。当我使用邮递员发出发布请求时,一切都很好,我的身份验证状态返回 true。很确定护照初始化是有序的,因为在邮递员中它工作得很好。令人困惑的是,我对两者使用相同的身体。 以快递方式发布请求:

router.post('/login', user_controller.user_login_post, (req, res) => {
  console.log(req.body);
  if (!req.user) {
    console.log('User not found!');
    res.send(req.body);
  } else {
    console.log('Signed in');
    res.send(req.body);
  }
});

控制器中的 login_post:

exports.user_login_post = passport.authenticate('local');
```

Auth checking in express/passport:
```
app.get('/api/checkauthentication', (req, res) => {
  req.isAuthenticated()
    ? res.status(200).json({ authenticated: true })
    : res.status(401).json({ authenticated: false });
});
```
Function I'm calling on submit in React:
```
  const login = (data) => {
    fetch('/api/users/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      credentials: 'include',
    })
      .then((response) => response.json())
      .then((data) => console.log('DATA: ', data))
      .catch((err) => {
        console.log('Error: ', err);
      });
  };
```

Also 'Signed in' gets logged out but auth only persists when I make the request from postman.

【问题讨论】:

    标签: node.js reactjs mongodb express authentication


    【解决方案1】:

    出现此问题是因为您使用 localhost。希望它可以帮助某人。

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      相关资源
      最近更新 更多