1

grunt-contrib-connectのミドルウェア オプションを使用して静的 json データをモックしますが、ミドルウェア関数には 2 つの引数しかなく、配列である必要がある 3 番目の引数は未定義であることがわかります。私のグラントファイル作品:

// 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 に答える