即使我声明了会话,快速会话也会返回“未定义”

时间:2018-12-17 06:24:55

标签: javascript express axios express-session

我已经在这个网站上工作了一段时间,并没有遇到任何问题,直到现在。

当用户登录时,会话cookie被初始化,该cookie称为用户并存储用户的电子邮件。当我声明登录后,在控制台上登录登录请求时记录cookie时,它将显示数据,但是当我更改路线(至其他路线)时。本地路由,该cookie不是永久性的,我的用户cookie更改为“未定义”。

发布请求,我正在使用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});
    });
});

家庭路线:

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
    }
});

中间件:

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);

这是我将数据发送到登录方法的方式。我使用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...';   
            }
        }
    }
});

知道为什么会这样吗?

****编辑****

更新:因此,确切地说,我正在使用cookie-parser模块来处理cookie,我决定使用它来初始化cookie。并返回此错误消息:

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)

以这种方式设置cookie:

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

1 个答案:

答案 0 :(得分:0)

由于错误状态,您已经发送完标头后就无法设置标头。

对于您而言,您要在结束响应后设置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);
});

在这种情况下,只需交换这两行就可以了:

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

尽管您可能只想在验证登录名之后才执行此操作(您在此代码块中实际上并未这样做)