表达奇怪的动态中间件行为4

时间:2015-02-04 16:40:34

标签: javascript node.js express

我试图在快速 4 路由中调用动态创建的中间件,但它永远不会被调用并创建超时。

'use strict';
var bodyParser = require( 'body-parser' );
var logger = require( './logger' );
var db = require( './mongoose' );
var validations = require( './validations' );

module.exports = function (app, config, done) {

    logger.debug( "Overriding 'Express' logger" );
    app.set( 'trust proxy', true );
    app.set( 'x-powered-by', false );

    app.use( require( 'morgan' )( 'dev', {"stream": logger.stream} ) );
    app.use( bodyParser.urlencoded( {extended: true} ) );

    app.post( '/api/login', [
        function (req, res, next) {
            console.log( 'check post' );
        },
        validations.login.post.validate,
        function (req, res, next) {
            console.log( 'Succeful post' );
            console.dir( req.user );
        }] );
};

这里validations.login.postValidationMiddleware类的对象,而validate方法是一个中间件,但它永远不会被调用。

var _ = require( 'lodash' );

var defaultOptions = {
    convert     : true,
    abortEarly  : false,
    stripUnknown: true
};

function ValidationMiddleware(schema, joi) {
    this.arr = {};
    this.joi = joi;
    if (!schema.options) schema.options = {};
    this.options = _.clone( _.defaults( schema.options, defaultOptions ) );
    if (schema.params && Object.getOwnPropertyNames( schema.params ).length > 0) this.arr['params'] = joi.compile( schema.params );
    if (schema.query && Object.getOwnPropertyNames( schema.query ).length > 0) this.arr['query'] = joi.compile( schema.query );
    if (schema.body && Object.getOwnPropertyNames( schema.body ).length > 0) this.arr['body'] = joi.compile( schema.body );
    //this.validate = this.validate.bind( this );
}

ValidationMiddleware.prototype.validate = function (req, res, next) {
    console.err("validate called")
    var parent = this;
    var flag = true;
    _.forEach( _.keys( this.arr ), function (key) {

        if (key == 'options') return true;
        var result = parent.joi.validate( req[key], parent.arr[key], parent.options );
        if (result.error) {
            res.status( 400 ).send( {
                message: 'incorrect values in ' + key,
                data   : result.error
            } );
            flag = false;
            return false;
        }
        //TODO: Assign values to
        req[key] = result.value;
    } );
    if (flag) next();

};

function ValidationMiddlewareBuilder(joi) {
    this.joi = joi;
    this.build = function (schema) {
        return new ValidationMiddleware( schema, joi );
    }
}

module.exports = ValidationMiddlewareBuilder;

我已经尝试过调试并登录到控制台,但在checkpost打印后没有任何内容。希望得到任何提示,以实现这一目标。我一直在使用另一个快速3项目,它仍在工作,但在这种情况下的东西设置它。当验证文件加载模式并创建动态ValidationMiddleware对象时,它似乎很罚款但是当路由被调用时,所有对象似乎都丢失了。

在另一个名为validations.js

的文件中调用构建方法
    fs
        .readdirSync( 'routes/validations' )
        .filter( function (file) {
            return (file.indexOf( '.' ) !== 0);
        } )
        .forEach( function (file) {
            console.log( 'Loading validation file ' + file );
            var models = new require( path.join( config.rootPath + '/routes/validations', file ) )( joi );
            var builder = new ValidationMiddlewareBuilder( joi );
            validations[file.split( '.' )[0]] = {};
            _.keys( models ).forEach( function (key) {
                validations[file.split( '.' )[0]][key] = builder.build( models[key] );
            } )
        } );

    module.exports = validations;

1 个答案:

答案 0 :(得分:1)

问题是您没有在第一个路由处理程序中调用next(),因此请求不会流向下一个处理程序(您的请求验证中间件)。由于您没有在第一个路由处理程序中返回响应,这就是您获得超时的原因。

请改为尝试:

app.post( '/api/login', [
    function (req, res, next) {
        console.log( 'check post' );
        next(); // <---- add this
    },
    validations.login.post.validate,
    function (req, res, next) {
        console.log( 'Succeful post' );
        console.dir( req.user );
    }] );

同样FWIW,你应该能够在不使用数组的情况下将多个中间件传递给路由功能。例如:

app.post( '/api/login',
    function (req, res, next) {
        console.log( 'check post' );
    },
    validations.login.post.validate,
    function (req, res, next) {
        console.log( 'Succeful post' );
        console.dir( req.user );
    } );