【问题标题】:Express-session returns 'undefined', even though I declared the session快速会话返回“未定义”,即使我声明了会话
【发布时间】:2018-12-17 06:24:54
【问题描述】:

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

当用户登录时,会初始化一个会话 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,确切地说,是使用 cookie-parser 模块,我决定用它初始化一个 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);
});

【问题讨论】:

  • “路由改变,cookie消失”是什么意思?我们需要查看初始化会话的代码和找不到会话的路由。向我们展示并准确记录您所做的和没有看到您所期望的。
  • 刚刚编辑
  • app.get()app.use() 这三个执行顺序是什么(会话中间件 vs. /home 路由定义 vs. /login 路由定义)。白路由注册排第一二三?
  • 当您从浏览器发出 Axios 请求时,您发出的请求是否与加载 Javascript 的网页完全相同的域、端口和协议?同源还是异源?我正在寻找 cookie 丢失的方法。可能需要在axios请求中设置withCredentials: true
  • 刚刚编辑,cookie-parser模块出错。

标签: javascript express axios express-session


【解决方案1】:

您无法在发送标头后设置标头,如您的错误所述。

在您的情况下,您在结束响应后设置 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);
});

虽然您可能只想在验证登录后才这样做(在此代码块中您并没有真正这样做)

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 2017-08-02
    • 2014-09-10
    • 2022-08-06
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多