为什么 grunt-contrib-connect 的中间件选项的第三个参数未定义?

Why the third arguments of middlewares option of grunt-contrib-connect is undefined?

我使用grunt-contrib-connect的中间件选项来模拟静态json数据,但是中间件函数只有2个参数,第三个应该是数组的参数结果是未定义的。 我的 gruntfile 片段:

// The actual grunt server settings
connect: {
    options: {
        port: 9000,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: '0.0.0.0'
    },
    server: {
        options: {
            open: 'http://localhost:9000',
            base: [
                '<%= yeoman.dist %>',
                '<%= yeoman.tmp %>',
                '<%= yeoman.app %>'
            ],
            middleware: function(connect, options, middlewares) {
                var bodyParser = require('body-parser');
                // the middlewares is undefined,so here i encountered an error.
                 middlewares.unshift(
                    connect().use(bodyParser.urlencoded({
                        extended: false
                    })),
                    function(req, res, next) {
                        if (req.url !== '/hello/world') return next();
                        res.end('Hello, world from port #' + options.port + '!');
                    }
                );
                return middlewares;
            }
        }
    },
    test: {
        options: {
            port: 9001,
            base: [
                '<%= yeoman.tmp %>',
                'test',
                '<%= yeoman.app %>'
            ]
        }
    },
    dist: {
        options: {
            open: true,
            base: '<%= yeoman.dist %>',
            livereload: false
        }
    }
},

错误是:

Running "connect:server" (connect) task
Warning: Cannot read property 'unshift' of undefined Use --force to continue.

Aborted due to warnings.

问题实际上并不是 middlewares 未定义。如果您有完整的堆栈跟踪,您会看到抛出的行实际上在您对 connect().use().

的调用中

您不能将对 use() 的调用取消转移到中间件数组上。相反,您应该只使用 bodyParser 生成的中间件,如下所示:

middlewares.unshift(
  bodyParser.urlencoded({
    extended: false
  }),
  function(req, res, next) {
    if (req.url !== '/hello/world') return next();
    res.end('Hello, world from port #' + options.port + '!');
  }
);