会话未存储在浏览器Cookie中

时间:2020-01-13 21:22:11

标签: javascript node.js express

当我尝试在邮递员中运行我的API时,它工作正常并且会话得到维护。但是,当我尝试从UI Part运行它时,登录会话无法正常工作。

这是我登录所在的登录API

app.post('/user/login', (req, res, next) => {
        const body = req.body;
        let email = body.email;
        let password = body.password;
        const userDetails = db.collection(userProfiles);
        userDetails.findOne({email: email}, function (err, user) {
            if (err) {
                return next(err);
            } else if (!user) {
                return res.status(400).send({
                    status: 'error',
                    message: 'user does not exist'
                });

            } else {
                if (user.password == password) {
                    user_object = user;
                    req.session.user = user;
                    return res.send({
                        user_obj: user,
                        status: 'success',
                        message: 'Successfully logged in'
                    });

                } else {
                    return res.status(400).send({
                        status: 'error',
                        message: 'Wrong Password'
                    })

                }
            }

            return res.send(user);
        });
    });

这是我的会话API,通过它我可以在调用此api时向用户发送req.session.user。

app.get('/user/dashboard', function (req, res) {
        if (!req.session.user) {
            return res.status(400).send({
                data:'need to be logged in'
            });
        }
        return res.status(200).send({
            data:req.session.user
        });
    });```



The below is the javascript file from where i am trying to call the user stores in req.session.user

`
async function fetchUserId(){
    let cookie = document.cookie;
    let res = await fetch('http://127.0.0.1:8080/user/dashboard',
        {redirect: 'follow',
            headers:{
                "Cookie":cookie
            }});
    let userJson = await res.json();
    console.log(res);
    console.log(userJson);
    //return userJson;
};
`


when i hit the login API from Postman it is maintaining session and working fine but when i do the same from UI from browser it is giving error status 400 every time. 

1 个答案:

答案 0 :(得分:0)

您可以做

fetch(url, options).then(function(res) { console.log(res} )

app.get('/user/dashboard', function (req, res) {
        console.log(req.headers)
        if (!req.session.user) {
            return res.status(400).send({
                data:'need to be logged in'
            });
        }
        return res.status(200).send({
            data:req.session.user
        });
    });

要检查cookie确实在那儿以及用户对象在哪里。

然后您可以检查您的浏览器开发控制台以查看cookie是否正在更新。

我看到这是提取请求,您在标题中放入了cookie。但是,除了在API之外,您还在req.session.user寻找用户。尽管cookie在req.header [“ Cookie”]中。