首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Express-session返回'undefined',即使我声明了session

Express-session返回'undefined',即使我声明了session
EN

Stack Overflow用户
提问于 2018-12-17 14:24:55
回答 1查看 424关注 0票数 0

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

当用户登录时,一个会话cookie被初始化,这个cookie被称为user,并存储用户的电子邮件。当我在控制台上将cookie记录在登录post请求上时,就在我声明它之后,它显示数据,但是,当我更改路由(到任何其他) ex。主路由,cookie不是持久的,并且我的用户cookie更改为“未定义”。

Post请求,我使用firebase API进行身份验证:

代码语言:javascript
复制
// 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});
    });
});

主路由:

代码语言:javascript
复制
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
    }
});

中间件:

代码语言:javascript
复制
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);

下面是我如何将数据发送到login方法。我使用Axios和Vue:

代码语言:javascript
复制
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,准确地说,是使用cookie解析器模块,我决定用它初始化cookie。并返回此错误消息:

代码语言:javascript
复制
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是这样设置的:

代码语言:javascript
复制
// Login GET Route
router.get('/login', (req, res) => {
    res.render('log_in.ejs');
    res.cookie('idk', 'idksj');
    console.log(req.cookies);
});
EN

回答 1

Stack Overflow用户

发布于 2018-12-18 03:55:54

正如您的错误所述,您不能在已经发送了头之后设置头。

在您的示例中,您将在结束响应后设置cookie标头:

代码语言:javascript
复制
// 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);
});

对于这种情况,您只需交换这两行代码就可以了:

代码语言:javascript
复制
// Login GET Route
router.get('/login', (req, res) => {
    res.cookie('idk', 'idksj');
    res.render('log_in.ejs');
    console.log(req.cookies);
});

尽管您可能只想在验证登录之后执行此操作(在此代码块中您实际上并没有执行此操作)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53809908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档