简体   繁体   English

即使我声明了会话,Express-session也会返回“ undefined”

[英]Express-session returns 'undefined', even though I declared the session

I've been working on this website for a while and didn't really have a problem, 'till now. 我已经在这个网站上工作了一段时间,并没有遇到任何问题,直到现在。

When the user logs in, a session cookie is initialized this cookie is called user and stores the users email. 当用户登录时,将初始化一个会话cookie,该cookie被称为用户并存储用户的电子邮件。 When I console log the cookie on the login post request, just after I declared it, it shows data, but, when I change of route (to any other) ex. 当我声明登录后,在控制台上登录登录请求时记录cookie时,它将显示数据,但是当我更改路线(至其他路线)时。 the home route, the cookie is not persistent and my user cookie changes to 'undefined'. 在本地路由上,该cookie并不是永久性的,并且我的用户cookie变为“未定义”。

Post Request, I'm using the firebase API for authentification: 发布请求后,我正在使用firebase API进行身份验证:

// Login POST Route
router.post('/login', (req, res) => {
    // Firebase authentication service
    firebase_user.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(data => {
        // Cookie Init
        req.session.user = req.body.email;
        console.log(req.session.user); // In here, cookie shows desired value
    }).catch(err => {
        res.send({"error": err.message});
    });
});

Home route: 出发路线:

router.get('/home', (req, res) => {
    // Check if Session Cookie Exists
    if (req.session.user) {
        res.render('home.ejs');
    } else {
        res.redirect('/login');
        console.log(req.session.user); // This console log shows 'undefined' even tho there the cookie was initialized correctly
    }
});

Middlewares: 中间件:

app.use(bodyParser.json());
app.use(morgan('combined'));
app.set('view engine', 'ejs');
app.use(express.static('./public'))
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({secret:"Testasl",resave:false,saveUninitialized:true,cookie:{secure:!true}}));

// Routes
app.use(routes);

And here is how I send the data to the login method. 这就是我将数据发送到登录方法的方式。 I use Axios and Vue: 我使用Axios和Vue:

var urlLog = 'http://localhost:3000/login';

new Vue({
    el: '#main',
    data: {
        email: '',
        password: '',
        showForm: true,
        showPreloader: false,
        errorMessage: '',
        errorShow: false

    },
    methods: {
        submitForm: function() {
            // Validates forms
            if (this.email!='' && this.password!=''){

                // Show Preloader
                this.showForm=false;
                this.showPreloader=true;

                // Ajax Post Request
                axios.post(urlLog, {
                    email: this.email,
                    password: this.password
                }).then(res => {
                    if (res.error){
                        // Shows form
                        this.showForm=true;
                        this.showPreloader=false;

                        // Shows Error
                        this.errorShow = true;
                        this.errorMessage = res.error;
                    } else {
                        // do nothing
                    }
                // Server Side error
                }).catch(err => {
                    console.log(err);
                });
            } else {
                this.errorShow = true;
                this.errorMessage = 'All fields are necessary...';   
            }
        }
    }
});

Any idea why this is happening??? 知道为什么会这样吗???

**** EDITED **** ****编辑****

UPDATE: So I was playing around with cookies, to be precise, with the cookie-parser module, and I decided to initialize a cookie with it. 更新:确切地说,我正在使用cookie解析器模块来处理cookie,我决定使用它来初始化cookie。 And returned this error message: 并返回此错误消息:

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:767:10)
    at ServerResponse.append (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:728:15)
    at ServerResponse.res.cookie (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:853:8)
    at router.get (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\bin\routes.js:74:9)
    at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)

The cookie was set in this way: Cookie是通过以下方式设置的:

// Login GET Route
router.get('/login', (req, res) => {
    res.render('log_in.ejs');
    res.cookie('idk', 'idksj');
    console.log(req.cookies);
});

You can't set a header after already sending the headers, as your error states. 由于错误状态,您无法在已发送标题后设置标题。

In your case, you're setting the cookie header after ending the response: 就您而言,您要在结束响应后设置Cookie标头:

// Login GET Route
router.get('/login', (req, res) => {
    res.render('log_in.ejs'); // completes the response
    res.cookie('idk', 'idksj'); // tries to set a cookie header
    console.log(req.cookies);
});

For this case, you would be well served to just swap those two lines: 对于这种情况,只需交换这两行就可以了:

// Login GET Route
router.get('/login', (req, res) => {
    res.cookie('idk', 'idksj');
    res.render('log_in.ejs');
    console.log(req.cookies);
});

Though you probably want to do that only after validating the login (which you're not really doing in this code block) 虽然您可能只想在验证登录名之后才执行此操作(您在此代码块中实际上并未这样做)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM