【发布时间】: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