1

I use middleware option of grunt-contrib-connect to mock static json data,but the middleware function only have 2 arguments,the third argument which should be an array turn outs to be undefined. my gruntfile piece:

// 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
        }
    }
},

The error is :

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

Aborted due to warnings.
Aflext
  • 309
  • 4
  • 15

1 Answers1

0

The issue is not actually that middlewares is undefined. If you had a full stack trace, you'd see that the line that is throwing is actually inside your call to connect().use().

You can't unshift a call to use() onto the middlewares array. Instead, you should just use the middleware generated by bodyParser, like this:

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 + '!');
  }
);
Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • Not working.Actually,when i print the `arguments`,it just shows 2 arguments .How to do a `full stack trace`? – Aflext Apr 10 '15 at 07:28
  • [`--stack`](https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js#L68): "Print a stack trace when exiting with a warning or fatal error" – Interrobang Apr 10 '15 at 07:32
  • I tracked into the source file and find out that the package is outdated even the version is the latest.So i reinstalled the package,it works! – Aflext Apr 10 '15 at 07:46