不能在单独的路由处理程序中使用快速会话

Cannot use express-session in separate route handler

我试图在单独的路由处理程序中使用快速会话中间件,但编译器抱怨 属性 'session' 在类型 'Request' 上不存在。

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;

我在网上找到的所有例子都说这应该有效,尽管大多数都不为路由处理程序使用单独的文件...

在您的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有一个默认会话存储,使用默认会话存储并检查是否仍然存在编译错误。

凭直觉,我尝试在不使用 TypeScript 的情况下创建相同的项目,但它成功了。一旦我知道 TS 是罪魁祸首,我就会很直接地发现我必须导入一个额外的节点包:@types/express-session