Wednesday, 7 June 2017

How can I write and read custom data from express-session using typescript?

I'm trying insert my data (like login or id) into a session. But when I'm writing req.session.login, typescript returns error: "Object is possibly 'undefined'." I was trying everything and I was looking for answer in google, but I didn't found anything.

Here is my 'src/app.ts' included into simple start file 'bin/www.js'.

import * as express from "express";
import * as session from 'express-session';
import * as cookieParser from "cookie-parser";

let app:express.Application = express();

app.use(cookieParser("sssh!"));
app.use(session({
    secret: 'sssssh! That\'s the secret',
    name: 'session',
    resave: false,
    saveUninitialized: true,
    cookie: {
      path: '*',
      maxAge: 60 * 60 * 1000,
      expires: new Date(Date.now() + (3 * 60 * 60 * 1000))
    }
}));
app.use("/test", (req:express.Request, res:express.Response, next:express.NextFunction)=>{
      let ses = req.session;
      // Here I want to do something similar to cookies, 
      //like req.session.login = "login" or ses.login = "login"
      res.cookie('name', "lastname");
      console.log(req.cookies);
      res.send(req.session);
});

If I'm not wrong, this declaration (req.session.login = "login") should work in normal javascript file. I'm sure that I missed something important here.



via Pampi

No comments:

Post a Comment