会话无法按预期工作

时间:2018-01-07 15:18:22

标签: node.js typescript session express-session

import * as express from 'express';
import * as session from 'express-session';
import * as bodyParser from 'body-parser';

const app: express.Express = express();

app.use(bodyParser.json());
app.use(session({
  secret: 'secret', resave: true,
  saveUninitialized: true, cookie: { maxAge: 60000 }
}));

app.post('/login', (req, res) => {
  req.session.username = 'test';
  res.send('login successfull');
});

app.post('/logout', (req, res) => {
  req.session.username = undefined;
  res.send('logged out successfully ' + req.session.username);
});

app.all('*', (req, res, next) => {
  console.log('should not be undefined ' + req.session.username);
  if (req.session.username !== undefined) {
    next();
  }
  res.send('username = ' + req.session.username);
  next();
});

app.post('/protected', (req, res) => {
  res.send('protected content')
})

app.listen(3000, () => { console.log('Server started on port 3000!'); });

问题是,在成功登录后,req.session.username仍未在其他路径中定义(app.all('*')....)。我把整个代码都搞了。请帮助我好几天......

1 个答案:

答案 0 :(得分:0)

import * as express from 'express';
import * as session from 'express-session';
import * as bodyParser from 'body-parser';

const app: express.Express = express();

/**
 * Make your function saperately check for permissions and if fails send them 403 or redirect them to login page
 */

function is_allowed() {
    return (req, res, next) => {
        if (req.session.username !== undefined) {
            next();
        } else {
            res.send(403);
        }
    }
}
app.use(bodyParser.json());
app.use(session({
    secret: 'secret', resave: true,
    saveUninitialized: true, cookie: { maxAge: 60000 }
}));

app.post('/login', (req, res) => {
    req.session.username = 'test';
    res.send('login successfull');
});

app.post('/logout', (req, res) => {
    req.session.username = undefined;
    res.send('logged out successfully ' + req.session.username);
});

// Use the permission in each route
app.post('/protected', is_allowed(), (req, res) => {
    res.send('protected content')
})

app.listen(3000, () => { console.log('Server started on port 3000!'); });