不能在单独的路由处理程序中使用express-session

时间:2018-03-21 11:57:56

标签: node.js typescript express express-session

我试图在单独的路由处理程序中使用快速会话中间件,但编译器抱怨属性“会话”#39;类型'请求'。

上不存在

app.ts

import debug = require('debug');
import express = require('express');
import path = require('path');
import db = require('diskdb');
import bodyParser = require('body-parser');
import session = require('express-session');
import fileStore = require('session-file-store');


import routes from './routes/index/index';
import users from './routes/user';
import register from './routes/users/register';
import login from './routes/users/login';

var app = express();

//Setup sesssion middleware
var sessionFileStore = fileStore(session);
app.use(session({
    name: 'server-session-cookie-id',
    secret: 'my express secret',
    saveUninitialized: true,
    resave: true,
    store: new sessionFileStore()
}));

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

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

app.use('/', routes);
app.use('/users', users);
app.use('/register', session, register);
app.use('/login', session, login);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err['status'] = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use((err: any, req, res, next) => {
        res.status(err['status'] || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use((err: any, req, res, next) => {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function () {
    debug('Express server listening on port ' + server.address().port);
});

login.ts

import express = require('express');
import path = require('path');
import bcrypt = require('bcrypt');

const router = express.Router();

router.get('/', (req: express.Request, res: express.Response) => {
    res.render(path.join(__dirname, 'login'), { message: 'display login form', username: '' });
});

router.post('/', (req: express.Request, res: express.Response) => {
    var un = req.body.username;
    var pw = req.body.password;

    var db = require('diskdb');
    db = db.connect('db', ['users']);

    var existing = db.users.findOne({ username: un });
    var all = db.users.find();

    bcrypt.compare(pw, existing != null ? existing.password : '', function (err, hashres) {
        // res == true
        if (hashres) {
            res.render(path.join(__dirname, 'login'), {
                message: ('handle login form submission for ' + un),
                username: un,
                result: "the username " + un + " is now logged in.",
                resulttype: "success"
            });
            req.session.user = un;
        }
        else {
            res.render(path.join(__dirname, 'login'), {
                message: ('handle login form submission for ' + un),
                username: un,
                result: "the username and password combination is incorrect.",
                resulttype: "error"
            });
        }
    });
});

export default router;

我在网上发现的所有例子都说这应该有效,不过大多数人都没有使用单独的档案来处理路线......

2 个答案:

答案 0 :(得分:1)

app.ts替换这些代码行

app.use('/register', session, register);
app.use('/login', session, login);

app.use('/register', register);
app.use('/login', login);

<强>更新 尝试通过此示例更新您的安装会话存储代码

var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({
    store: new FileStore(options),
    ...
}));

如果仍然不起作用,express-session有一个默认的会话存储,使用默认的会话存储并检查是否还有编译错误。

答案 1 :(得分:0)

在预感中,我试图在没有TypeScript的情况下创建相同的项目,并且它有效。一旦我知道TS是罪魁祸首就很容易发现我必须导入一个额外的节点包:@types/express-session