在以下路线上,我可以访问用户信息,因为我设置了此cookie,例如,我可以获取用户信息:
// Get Current Logged In User
router.get('/user/current_user', (req, res, next) => {
userModel.findById(req.session.user_id, (error, returnedDocuments) => {
if (error) return next(error);
res.json(returnedDocuments);
});
});
当我尝试使用前端登录用户,在后端接收到请求并且得到此响应时,会发生我的问题
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: false } }
但是在前端,我无法访问cookie,它在本地存储中不存在
然后,当我尝试请求获取用户信息时,例如,如果我想在页面加载时使用效果以设置有关是否登录用户的状态,则无法执行此操作...
useEffect(
() => {
axios
.get('http://localhost:3000/api/post/user/current_user')
.then(({ data }) => {
dispatch(login())
console.log(data)
})
.catch((err) => {
console.log(err);
});
},
[dispatch]
);
我遇到了这个错误:
Error: You are not authenticated! __
因为我无法通过身份验证功能
function auth(req, res, next) {
console.log(req.session); // express.session will provide this in the request
console.log('req.header', req.headers);
if (!req.session.user) {
// if express.session did not set a user
var err = new Error('You are not authenticated! __');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 403; // forbidden access , they have to go to /users/login or /users/register route to get access
return next(err);
} else {
if (req.session.user === 'authenticated') {
// we set thjs string in /users/login when client login
next();
} else {
let err = new Error('You are not authenticated!');
err.status = 403;
return next(err);
}
}
}
如果有人有想法,请告诉我。...