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

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

本文关键字:三个 参数 未定义 contrib grunt connect 中间件 为什么 选项      更新时间:2023-09-26

我使用grunt contrib connect的中间件选项来模拟静态json数据,但中间件函数只有两个参数,第三个参数本应是数组,但结果没有定义。我的文章:

// 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 + '!');
  }
);