Express-Session is undefined

江枫思渺然 提交于 2019-12-11 05:43:17

问题


I am new to node.js and angular4 and am working on an application which required user authentication. I want to save the user role in a session in node.js and want to access that session in multiple routes. However, I am unable to get the role in other routes. I have checked many answers regarding the same but none have worked for me so far. Scenario: I have implemented Express-Session in app.js

const session = require('express-session');
const cookieParser = require('cookie-parser')
const app = express();
const port = 4000;

app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());

app.all('*',function(req, res, next){
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header("Access-Control-Allow-Credentials", "true");
next();
});

app.use(cookieParser())
app.use(session({secret: "my secret", resave: false, saveUninitialized: true, cookie: { secure: !true }}));

I have a file named user.js which is being used for login user. After successful verification, user information is stored in a session.

res.json({
      success: true,
      token: 'JWT ' + token,
      user: {
          id: user[0].UserId,
          FirstName: user[0].FirstName,
          MiddleName: user[0].MiddleName,
          LastName: user[0].LastName,
          EmailID: user[0].EmailID,
          PhoneNo: user[0].PhoneNo,
          Role: user[0].Role,
          DistrictId: user[0].DistrictId
        },
    });
    req.session.userRole = user[0].Role;
    req.session.save();

At this point, req.session.userRole has the user role.

However, when I use req.session.userRole in another route, eg: dept.js, it shows undefined.

Also, when I use Chrome app: Postman, it displays

Session {
   cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: false },
    userRole: 'ADMN' }

But when I run the application which is using Angular4, it just shows

Session {
   cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: false }

PS: Node.js app is on port: 4000 and angular4 app is on 4200.

Thanks in Advance.

来源:https://stackoverflow.com/questions/44513553/express-session-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!