1

我使用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.
4

1 回答 1

0

这个问题实际上并不是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 + '!');
  }
);
于 2015-04-10T07:14:52.703 回答