Coder Social home page Coder Social logo

grunt-contrib-connect's Introduction

grunt-contrib-connect v4.0.0 Build Status

Start a connect web server

Getting Started

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-contrib-connect --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-contrib-connect');

Connect task

Run this task with the grunt connect command.

Note that this server only runs as long as grunt is running. Once grunt's tasks have completed, the web server stops. This behavior can be changed with the keepalive option, and can be enabled ad-hoc by running the task like grunt connect:keepalive.

This task was designed to be used in conjunction with another task that is run immediately afterwards, like the grunt-contrib-qunit plugin qunit task.

Options

port

Type: Integer
Default: 8000

The port on which the webserver will respond. The task will fail if the specified port is already in use (unless useAvailablePort is set). You can use the special values 0 or '?' to use a system-assigned port.

protocol

Type: String
Default: 'http'

May be 'http', 'http2' or 'https'.

hostname

Type: String
Default: '0.0.0.0'

The hostname on which the webserver can be accessed.

Setting it to '*', like '0.0.0.0', will make the server accessible from any local IPv4 address like '127.0.0.1' and the IP assigned to an ethernet or wireless interface (like '192.168.0.x' or '10.0.0.x'). More info

If open is set to true, the hostname setting will be used to generate the URL that is opened by the browser, defaulting to localhost if a wildcard hostname was specified.

base

Type: String or Array or Object
Default: '.'

Type Result Example
String The base (or root) directory from which files will be served. Defaults to the project Gruntfile's directory. 'public'
Array Array of String (or Object) bases to serve multiple directories. The last base given will be the [directory][] to become browse-able. ['public','www-root']
Object Map containing path and options keys. options are passed on to the serve-static module. { path: 'public', options: { maxAge: 1000*60*5 } }

directory

Type: String
Default: null

Set to the directory you wish to be browse-able. Used to override the base option browse-able directory.

See https://www.npmjs.com/package/serve-index for details.

keepalive

Type: Boolean
Default: false

Keep the server alive indefinitely. Note that if this option is enabled, any tasks specified after this task will never run. By default, once grunt's tasks have completed, the web server stops. This option changes that behavior.

This option can also be enabled ad-hoc by running the task like grunt connect:targetname:keepalive

debug

Type: Boolean
Default: false

Set the debug option to true to enable logging instead of using the --debug flag.

livereload

Type: Boolean, Number, or Object
Default: false

Set to anything but false to inject a live reload script tag into your page using connect-livereload.

If you set to true, defaults are used. If you set to a number, that number is used as a port number, together with the hostname you configured. If you set this to an object, that object is passed to connect-livereload unchanged as its configuration.

This does not by itself perform live reloading. It is intended to be used in tandem with grunt-contrib-watch or another task that will trigger a live reload server upon files changing.

open

Type: Boolean or String or Object
Default: false

Open the served page in your default browser.

This can be one of the following:

  • Specifying true opens the default server URL (generated from the protocol, hostname and port settings)

  • Specifying a URL opens that URL

  • Specify an object with the following keys to configure opn directly:

     {
       target: 'http://localhost:8000', // target url to open
       appName: 'open', // name of the app that opens, ie: open, start, xdg-open
       callback: function() {} // called when the app has opened
     }

Note that in v0.9.0 open was replaced with opn but the configuration remained the same for backwards compatibility. target, appName and callback are the only supported keys in the config object.

useAvailablePort

Type: Boolean
Default: false

If true the task will look for the next available port after the set port option.

onCreateServer

Type: Function or Array
Default: null

A function to be called after the server object is created, to allow integrating libraries that need access to connect's server object. A Socket.IO example:

grunt.initConfig({
  connect: {
    server: {
      options: {
        port: 8000,
        hostname: '*',
        onCreateServer: function(server, connect, options) {
          var io = require('socket.io').listen(server);
          io.sockets.on('connection', function(socket) {
            // do something with socket
          });
        }
      }
    }
  }
});

middleware

Type: Function or Array
Default: Array of connect middlewares that use options.base for static files and directory browsing

As an Array:

grunt.initConfig({
  connect: {
    server: {
      options: {
        middleware: [
          function myMiddleware(req, res, next) {
            res.end('Hello, world!');
          }
        ],
      },
    },
  },
});

As a function:

grunt.initConfig({
  connect: {
    server: {
      options: {
        middleware: function(connect, options, middlewares) {
          // inject a custom middleware into the array of default middlewares
          middlewares.unshift(function(req, res, next) {
            if (req.url !== '/hello/world') return next();

            res.end('Hello, world from port #' + options.port + '!');
          });

          return middlewares;
        },
      },
    },
  },
});

Lets you add in your own Connect middlewares. This option expects a function that returns an array of middlewares. See the project Gruntfile and project unit tests for a usage example.

Usage examples

Basic Use

In this example, grunt connect (or more verbosely, grunt connect:server) will start a static web server at http://localhost:9001/, with its base path set to the www-root directory relative to the gruntfile, and any tasks run afterwards will be able to access it.

// Project configuration.
grunt.initConfig({
  connect: {
    server: {
      options: {
        port: 9001,
        base: 'www-root'
      }
    }
  }
});

If you want your web server to use the default options, just omit the options object. You still need to specify a target (uses_defaults in this example), but the target's configuration object can otherwise be empty or nonexistent. In this example, grunt connect (or more verbosely, grunt connect:uses_defaults) will start a static web server using the default options.

// Project configuration.
grunt.initConfig({
  connect: {
    uses_defaults: {}
  }
});

Multiple Servers

You can specify multiple servers to be run alone or simultaneously by creating a target for each server. In this example, running either grunt connect:site1 or grunt connect:site2 will start the appropriate web server, but running grunt connect will run both. Note that any server for which the keepalive option is specified will prevent any task or target from running after it.

// Project configuration.
grunt.initConfig({
  connect: {
    site1: {
      options: {
        port: 9000,
        base: 'www-roots/site1'
      }
    },
    site2: {
      options: {
        port: 9001,
        base: 'www-roots/site2'
      }
    }
  }
});

Static Options

Options for the serve-static module. See serve-static:

grunt.initConfig({
  connect: {
    server: {
      options: {
        port: 8000,
        base: {
          path: 'www-root',
          options: {
            index: 'somedoc.html',
            maxAge: 300000
          }
        }
      }
    }
  }
});

Roll Your Own

Like the Basic Use example, this example will start a static web server at http://localhost:9001/, with its base path set to the www-root directory relative to the gruntfile. Unlike the other example, this is done by creating a brand new task. in fact, this plugin isn't even installed!

// Project configuration.
grunt.initConfig({ /* Nothing needed here! */ });

// After running "npm install connect serve-static --save-dev" to add connect as a dev
// dependency of your project, you can require it in your gruntfile with:
var connect = require('connect');
var serveStatic = require('serve-static');
connect(serveStatic('www-root')).listen(9001);

// Now you can define a "connect" task that starts a webserver, using the
// connect lib, with whatever options and configuration you need:
grunt.registerTask('connect', 'Start a custom static web server.', function() {
  grunt.log.writeln('Starting static web server in "www-root" on port 9001.');
  connect(serveStatic('www-root')).listen(9001);
});

Support for HTTPS / HTTP2

A default certificate authority, certificate and key file are provided and pre- configured for use when protocol has been set to https.

NOTE: No passphrase set for the certificate. If you are getting warnings in Google Chrome, add 'server.crt' (from 'node_modules/tasks/certs') to your keychain. In OS X, after you add 'server.crt', right click on the certificate, select 'Get Info' - 'Trust' - 'Always Trust', close window, restart Chrome.

For HTTPS / HTTP2 livereload with grunt-contrib-watch see the last example here.

Advanced HTTPS / HTTP2 config

If the default certificate setup is unsuitable for your environment, OpenSSL can be used to create a set of self-signed certificates with a local ca root.

### Create ca.key, use a password phrase when asked
### When asked 'Common Name (e.g. server FQDN or YOUR name) []:' use your hostname, i.e 'mysite.dev'
openssl genrsa -des3 -out ca.key 1024
openssl req -new -key ca.key -out ca.csr
openssl x509 -req -days 365 -in ca.csr -out ca.crt -signkey ca.key

### Create server certificate
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr

### Remove password from the certificate
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

### Generate self-siged certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

For more details on the various options that can be set when configuring SSL, please see the Node documentation for TLS.

Grunt configuration would become

// Project configuration.
grunt.initConfig({
  connect: {
    server: {
      options: {
        protocol: 'https', // or 'http2'
        port: 8443,
        key: grunt.file.read('server.key').toString(),
        cert: grunt.file.read('server.crt').toString(),
        ca: grunt.file.read('ca.crt').toString()
      },
    },
  },
});

Grunt Events

The connect plugin will emit a grunt event, connect.{taskName}.listening, once the server has started. You can listen for this event to run things against a keepalive server, for example:

grunt.registerTask('jasmine-server', 'start web server for jasmine tests in browser', function() {
  grunt.task.run('jasmine:tests:build');

  grunt.event.once('connect.tests.listening', function(host, port) {
    var specRunnerUrl = 'http://' + host + ':' + port + '/_SpecRunner.html';
    grunt.log.writeln('Jasmine specs available at: ' + specRunnerUrl);
    require('open')(specRunnerUrl);
  });

  grunt.task.run('connect:tests:keepalive');
});

Release History

  • 2023-07-13โ€ƒโ€ƒโ€ƒv4.0.0โ€ƒโ€ƒโ€ƒRequires node 16+. Updated dependencies.
  • 2020-07-16โ€ƒโ€ƒโ€ƒv3.0.0โ€ƒโ€ƒโ€ƒRequires node 10+. Updated dependencies.
  • 2019-09-03โ€ƒโ€ƒโ€ƒv2.1.0โ€ƒโ€ƒโ€ƒUpdate package lock. Allow all configuration options of livereload to be passed through.
  • 2018-09-09โ€ƒโ€ƒโ€ƒv2.0.0โ€ƒโ€ƒโ€ƒDrop Node.js < 6 support. Update all dependencies and switch to node-http2. Add secureProtocol in httpsOptions. Fix open.appName. Allow passing serve-index options.
  • 2016-04-27โ€ƒโ€ƒโ€ƒv1.0.2โ€ƒโ€ƒโ€ƒFixed http2 dependencies and stopped using the fork.
  • 2016-03-22โ€ƒโ€ƒโ€ƒv1.0.1โ€ƒโ€ƒโ€ƒFixed dependencies behind corporate proxy server.
  • 2016-03-04โ€ƒโ€ƒโ€ƒv1.0.0โ€ƒโ€ƒโ€ƒUse predefined logger format with colored http status. Update deps and docs. HTTP2 support. Other fixes.
  • 2015-08-03โ€ƒโ€ƒโ€ƒv0.11.2โ€ƒโ€ƒโ€ƒDocumentation fixes.
  • 2015-08-01โ€ƒโ€ƒโ€ƒv0.11.1โ€ƒโ€ƒโ€ƒFixes debug logging.
  • 2015-07-30โ€ƒโ€ƒโ€ƒv0.11.0โ€ƒโ€ƒโ€ƒUpdate to connect 3.
  • 2015-04-03โ€ƒโ€ƒโ€ƒv0.10.1โ€ƒโ€ƒโ€ƒFixes npm corruption issue.
  • 2015-04-03โ€ƒโ€ƒโ€ƒv0.10.0โ€ƒโ€ƒโ€ƒNode.js 0.12 fixes. Doc updates. Fixes port finding. Other fixes.
  • 2014-11-07โ€ƒโ€ƒโ€ƒv0.9.0โ€ƒโ€ƒโ€ƒAdds routable middleware. Switch to opn as it fixes some Linux issues. Add support for connect.static instance options.
  • 2014-06-09โ€ƒโ€ƒโ€ƒv0.8.0โ€ƒโ€ƒโ€ƒUpdate connect and connect-livereload.
  • 2014-02-27โ€ƒโ€ƒโ€ƒv0.7.1โ€ƒโ€ƒโ€ƒFixes issue with the '*' hostname option.
  • 2014-02-18โ€ƒโ€ƒโ€ƒv0.7.0โ€ƒโ€ƒโ€ƒUpdate connect to ~2.13.0. Default hostname switched to 0.0.0.0. Modified options.middleware to accept an array or a function.
  • 2013-12-29โ€ƒโ€ƒโ€ƒv0.6.0โ€ƒโ€ƒโ€ƒOpen options.hostname if provided. Update connect-livereload to ~0.3.0. Update connect to ~2.12.0. Use well-formed SSL certificates. Support all options of open. Make directory browseable when base is a string.
  • 2013-09-05โ€ƒโ€ƒโ€ƒv0.5.0โ€ƒโ€ƒโ€ƒAdd open option.
  • 2013-09-05โ€ƒโ€ƒโ€ƒv0.4.2โ€ƒโ€ƒโ€ƒUn-normalize options.base as it should be a string or an array as the user has set. Fix setting target hostname option.
  • 2013-09-02โ€ƒโ€ƒโ€ƒv0.4.1โ€ƒโ€ƒโ€ƒBrowse-able directory is the last item supplied to bases. Added directory option to override browse-able directory.
  • 2013-09-01โ€ƒโ€ƒโ€ƒv0.4.0โ€ƒโ€ƒโ€ƒFix logging of which server address. Ability to set multiple bases. Event emitted when server starts listening. Support for HTTPS. debug option added to display debug logging like the --debug flag. livereload option added to inject a livereload snippet into the page.
  • 2013-04-10โ€ƒโ€ƒโ€ƒv0.3.0โ€ƒโ€ƒโ€ƒAdd ability to listen on system-assigned port.
  • 2013-03-07โ€ƒโ€ƒโ€ƒv0.2.0โ€ƒโ€ƒโ€ƒUpgrade connect dependency.
  • 2013-02-17โ€ƒโ€ƒโ€ƒv0.1.2โ€ƒโ€ƒโ€ƒEnsure Gruntfile.js is included on npm.
  • 2013-02-15โ€ƒโ€ƒโ€ƒv0.1.1โ€ƒโ€ƒโ€ƒFirst official release for Grunt 0.4.0.
  • 2013-01-18โ€ƒโ€ƒโ€ƒv0.1.1rc6โ€ƒโ€ƒโ€ƒUpdating grunt/gruntplugin dependencies to rc6. Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
  • 2013-01-09โ€ƒโ€ƒโ€ƒv0.1.1rc5โ€ƒโ€ƒโ€ƒUpdating to work with grunt v0.4.0rc5.
  • 2012-11-01โ€ƒโ€ƒโ€ƒv0.1.0โ€ƒโ€ƒโ€ƒWork in progress, not yet officially released.

Task submitted by "Cowboy" Ben Alman

This is a generated file.

grunt-contrib-connect's People

Contributors

alampros avatar alexstrat avatar alextreppass avatar atesgoral avatar cebor avatar cowboy avatar dependabot[bot] avatar eddiemonge avatar fardog avatar iristyle avatar jaredstehler-cengage avatar johngeorgewright avatar jubalm avatar lukeapage avatar mannyc avatar mzgoddard avatar ngryman avatar philippsoehnlein avatar radkodinev avatar shama avatar sindresorhus avatar stevemao avatar thegreatrefrigerator avatar theturtle32 avatar thisgeek avatar timkendrick avatar vladikoff avatar warpdesign avatar xhmikosr avatar yogu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-contrib-connect's Issues

Is it possible to configure the mime type returned by grunt-contrib-connect?

I have a specific file in my app that I need to return as a mime type of text/cache-manifest. The rest should be served just like grunt-contrib-connect normally does. Is it possible to configure grunt-contrib-connect this way? If I had to guess, it would have something to do with the middleware but I don't see an example of how to do this.

If anyone cares why I need this, it's because I've got a static html5 webapp, and I need to force it to be cached on my iPad. To do that, I need to follow these directions: https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/Client-SideStorage/Client-SideStorage.html

If this is already possible, I'm requesting documentation. If it's not possible, I'm requesting this feature. Thanks

Can't install on Windows 7 64bits

28354 error Error: ENOENT, lstat 'C:\Users\Webdev\Inetpub\gym\node_modules\grunt-contrib\node_modules\grunt-contrib-connect\node_modules\connect\lib\public\style.css'
28355 error If you need help, you may report this log at:
28355 error     <http://github.com/isaacs/npm/issues>
28355 error or email it to:
28355 error     <[email protected]>
28356 error System Windows_NT 6.1.7601
28357 error command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
28358 error cwd C:\Users\Webdev\Inetpub\gym
28359 error node -v v0.8.22
28360 error npm -v 1.2.14
28361 error path C:\Users\Webdev\Inetpub\gym\node_modules\grunt-contrib\node_modules\grunt-contrib-connect\node_modules\connect\lib\public\style.css
28362 error fstream_path C:\Users\Webdev\Inetpub\gym\node_modules\grunt-contrib\node_modules\grunt-contrib-connect\node_modules\connect\lib\public\style.css
28363 error fstream_type File
28364 error fstream_class FileWriter
28365 error code ENOENT
28366 error errno 34
28367 error fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
28367 error fstream_stack Object.oncomplete (fs.js:297:15)
28368 verbose exit [ 34, true ]

node 0.8.22, npm 1.2.14, Windows 7 64bits

Process hangs after test-plugin failure using recent grunt commits (with node-exit)

I have a problem where a failure in my test suite won't close the grunt node process if I use grunt-contrib-connect.

This does not happen in release version of grunt, only in recent commits:

I'm working on Windows Vista 64 and use one of the recent grunt commits as my dependency because I need the node-exit fixes instead of the npm published 0.4.1.

My test are in mocha, and run with grunt-mocha-test. This usually feels very dependable, until I needed to add some http-tests with grunt-contrib-connect.


When my unit tests all pass the node process exits as expected.

When a test fails (and so the task that runs it) I see its report, grunt's feedback and the Aborted due to warnings. message, but the process doesn't exit. If I check my task manager I see the node.js still remains active.

This confirms when I run the same grunt tasks again after a failure: I get the 'port in use' message when the connect task attempts started on same port again.

If I revert my grunt dependency to the npm version the process exits as expected after a test suite failure.

If I keep the recent grunt commit but use an separated (keep-alive) connect server in it's own shell everything also works as expected.

So it looks like the combination of [recent grunt * grunt-contrib-connect * task failure] keeps a lingering listener alive.


It is part of a larger project, if you want a demo I can extract and commit a minimal proof somewhere.

Update to connect 2.11.2

Update to the latest version of "connect", which is 2.11.2

Seems like there are some issues with multi-base paths, tests are failing.

TLS / SSL / https support

It can be useful to fire up a https server, particularly when dealing with simulating CORS requests to a remote server that requires https.

This is something Connect has the ability to handle... assuming that the appropriate options are passed to Nodes https.createServer, which is then passed the Connect object to wrap as seen in [this example]{https://github.com/senchalabs/connect/blob/master/lib/proto.js#L214).

The bigger issue would be how to address passing options if you want to fire up both a http and https server on different ports, etc, etc.

So tossing it out there to see if this is something that would make sense / others see benefit in.

LiveReload snippet will not be injected into HTML when using query params in URL

Here is the related part of my Gruntfile:

connect:
    staging:
        options:
          port: 9000
          hostname: "*" # Allows to use IP address instead of 'localhost'
          livereload: on
          middleware: (connect) ->
            [
              proxySnippet
              mountFolder(connect, "public")
            ]

I'm using grunt-connect-proxy but I've tried removing it completely without any luck.

mountFolder looks like:

mountFolder = (connect, dir) ->
  connect.static require("path").resolve(dir)

Adding middleware which supports get & post URL like expressjs

Hi Creator,

Would you like to recommend which package can be integrated with grunt-contrib-connect and support post & get URL like epxressjs?

The reason is that in small & medium project, I would like to use yeoman angularjs generator and reuse the same server for API.

I already implemented grunt-contrib-connect middleware function to provide get & post but still can not be powerful like expressjs (at least, I need more time in order to improve it). I am looking for some exists package but still can not find the right one.

Thanks,
Henry

Add custom middleware without overwriting the default ones

I'd like to add just a single middleware (modrewrite) to existing ones and configure serving static files via base option. However, providing middleware option overwrites the default middleware stack.

connect: {
  livereload: {
    base: [
      '.tmp',
      '<%= yeoman.app %>'
    ],
    options: {
      middleware: function (connect, options) {
        return [
          require('connect-modrewrite')([
            '!\\.ttf|\\.woff|\\.ttf|\\.eot|\\.html|\\.js|\\.css|\\.png|\\.jpg|\\.gif|\\.svg$ /index.html [L]'
          ])
        ];
      }
    }
  }
}

It would be great if there was a way to just add new middlewares to the stack.

It possibly could be done by providing the default stack (one returned by the default middleware function) that would be passed to custom middleware function as a third argument:

// connect.js file
var options = this.options({
  ...
  middleware: function(connect, options, stack) { return stack; }
});

var stack = function(connect, options) {
  var middlewares = [];
  // the default middleware stack
  return middlewares;
}.call(this, connect, options);

var middleware = options.middleware ? options.middleware.call(this, connect, options, stack) : stack;

I'm not sure if this is going to work, but at least in theory it should allow to add a new middleware to an existing stack:

middleware: function (connect, options, stack) {
  stack.unshift(require('connect-modrewrite')([...]);
  return stack;
}

One could also overwrite the default stack by simply returning a new stack from middleware function (the current behavior) e.g.:

middleware: function (connect, options) {
  return [connect.static("/")];
}

Connect cannot start on any port - EADDRNOTAVAIL

โžœ  sample-simple-app git:(master) โœ— grunt
Running "connect:server:keepalive" (connect) task
Starting connect web server on localhost:9190.
Waiting forever...
Fatal error: listen EADDRNOTAVAIL

I am continually getting this error even when I change the port to 8000, 8080, 9001, etc. I have tried sudo killall node and I have run "ps aux | grep node" and I do not have any node processes running. I have also checked netstart and do not have anything running on those ports.

It appears that somehow grunt or connect is persisting this server? I have keepalive on there, but I usually terminate the process with Control + C. Yesterday, it would sometimes work and sometimes give me this error, but now I get it all the time.

Here's the Gruntfile

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        options: {
          port: 9190,
          keepalive: false,
        }
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    },
    jasmine: {
      test: {
        src: 'app/**/*.js',
        options: {
          specs: 'test/*.spec.js',
          helpers: 'test/*.helper.js',
          host: 'http://127.0.0.1:8080'
        }
      }
    }
  });

  // A basic server for testing the app - this server only runs while grunt is running. Use keepalive: true for use as a development server
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Load the plugin for Jasmine bdd testing
  grunt.loadNpmTasks('grunt-contrib-jasmine');

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['connect:server:keepalive']);
  grunt.registerTask('test', ['connect:server', 'jasmine:test']);

};

I'm on Mac OSX Mountain Lion (UNIX) and I have node 0.8.15, grunt-cli v0.1.7, grunt v0.4.1.

hostname: '*' does not work on Windows

Running "connect:devel" (connect) task
Starting connect web server on *:8000.
Waiting forever...
Fatal error: getaddrinfo ENOENT

On Windows, you have to use '0.0.0.0' instead of '*'. Please either note this in the docs or add support for the translation under the hood.

When will connect-livereload 0.3.0 be used?

There's a rather big bug fix in 0.3.0: intesso/connect-livereload#13
However when using yo webapp generator, it still shows:
[email protected] node_modules\grunt-contrib-connect
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ””โ”€โ”€ [email protected] ([email protected], [email protected], [email protected], pau
[email protected], [email protected], [email protected], [email protected], [email protected], [email protected], s
[email protected])

Not sure if this is a good place to ask question since a lot has changed with the new grunt version, but still hoping to get some help.

Thanks!

provide a way to add event listeners to the server object

I'm reverse proxying certain URLs during development, and need to reverse proxy a websocket connection. This requires adding an .on('upgrade') listener to the server, as shown here: https://github.com/nodejitsu/node-http-proxy#proxying-websockets

I don't see any way to access the actual instantiated server object in order to add the event listener in a Gruntfile. The setup callback proposed in #26 would work, as would some kind of explicit on('upgrade') configuration option.

Add 404 page

Right now if I specify a path that doesn't exist I get a page that says:

Cannot GET /some/path

Would be nice to specify a 404.html file instead. Or, in the case of angularjs apps would like to specify index.html to handle routing.

Is session storage possible

I have been looking through the features / examples and I can't figure out if it would be possible to get this to use a session store such as connect-mongo ?

something like

var connect = require('connect');
var MongoStore = require('connect-mongo')(connect);
var app = connect ();

app.use(express.session({
    store: new MongoStore({
      url: 'mongodb://' + settings.database.host + '/' + settings.database.name + 'store'            'mongodb://root:[email protected]:27017/3xam9l3'
    }),
    secret: 'secrethere'
  }));

I was thinking it might be possible like grunt-express where you can set server option to point to a file which exports a connect/express object ?

Keepalive option

I'm not sure if i should open an issue here, or just ask on irc (nobody was available to answer) but I don't understand the purpose of the keepalive option from what i understand this option should be enabled if i want my server to be on after the task has finished, why would i want otherwise? I can't think of any scenario where i get a server that turns on and off immediately after the task has finished.
Or maybe I'm getting it wrong :)

error on run

TypeError: Object # has no method 'options'
at Object.module.exports (/projects/sony/global/src/node_modules/grunt-contrib-connect/tasks/connect.js:22:24)
at Object.task.registerMultiTask.thisTask (/projects/sony/global/src/node_modules/grunt/lib/grunt/task.js:109:15)
at Object.task.registerTask.thisTask.fn (/projects/sony/global/src/node_modules/grunt/lib/grunt/task.js:58:16)
at Task. (/projects/sony/global/src/node_modules/grunt/lib/util/task.js:343:36)
at Task. (/projects/sony/global/src/node_modules/grunt/lib/util/task.js:319:9)
at Task. (/projects/sony/global/src/node_modules/grunt/lib/util/task.js:346:11)
at Task.start (/projects/sony/global/src/node_modules/grunt/lib/util/task.js:359:5)
at Object.grunt.tasks (/projects/sony/global/src/node_modules/grunt/lib/grunt.js:143:8)
at Object.module.exports as cli
at Object. (/usr/local/lib/node_modules/grunt/bin/grunt:19:14)

TypeError: Object ... has no method 'charAt'

Maybe it is somehow connected with connect-modrewrite plugin...

TypeError: Object /home/[...]/public has no method 'charAt'
    at exports.normalize (path.js:336:27)
    at SendStream.root.SendStream.from (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/node_modules/send/lib/send.js:116:16)
    at Object.static (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/lib/middleware/static.js:79:8)
    at next (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
    at Object.handle (/home/[...]/node_modules/connect-modrewrite/src/modrewrite.js:115:7)
    at next (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
    at Function.app.handle (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:198:3)
    at Server.app (/home/[...]/node_modules/grunt-contrib-connect/node_modules/connect/lib/connect.js:65:37)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2045:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
    at Socket.socket.ondata (http.js:1935:22)
    at TCP.onread (net.js:524:27)

404 errors

I'm using the default [https://github.com/yeoman/generator-webapp](yeoman webapp); this may be better suited for them, though.

I can browse a directory when I use the standard grunt serve task, which is what I want; however, if I run grunt serve:dist I cannot browse the directory.

I can open files in the directory but not the directory.
Locally, the permissions of app and dist are the same.

Am I doing something wrong, missing an option, looking at the wrong plugin, or is this the intended behavior?

Thanks

Using connect with watch to serve results in EADDRINUSE

I'm trying to set up a server using connect that reloads when a watched file changes. I've set this up as a serve task

grunt.registerTask("serve", ["connect", "watch"]);

The server starts fine the first time, but after a change is made, I get an EADDRINUSE error, and any subsequent watched changes aren't picked up. The server does continue to stay up, however.

Here is a pared down version of the Gruntfile I'm working with. https://gist.github.com/3989392

I'm not 100% sure that this isn't a watch issue. If anyone thinks that might be the case, I can move this issue there.

Change default IP from "localhost" to "0.0.0.0"

By specifying 0.0.0.0, the server will bind to all IPs, allowing both "localhost" to continue to work (locally) as well as allowing the server to be accessed from external devices via the machine's IP or hostname.

Will this cause any problems? We would have to bump the minor version, but this change is awesome in my testing, here.

Any downsides?

Bump npm repo version to updated source on github

Using "grunt-contrib-connect": "~0.5.0" in package.json doesn't get latest source for task.
Workaround is to use "grunt-contrib-connect": "gruntjs/grunt-contrib-connect#7fdf7adb0608f6fdb734df58a6b11b07ad55cc9f"

When will this be fixed?

Pretty URL in connect server

I have links like /about, /contact without .html extension. But the connect server always expect about.html and contact.html.

Is there any option to achieve pretty URL?

https not working on firefox

certificate is invalid and no exception is let through

Secure Connection Failed

            An error occurred during a connection to localhost:9000.

Peer's certificate has an invalid signature.

(Error code: sec_error_bad_signature)

The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
Please contact the website owners to inform them of this problem. Alternatively, use the command found in the help menu to report this broken site.

might be related to #15 (comment)

Middleware seemingly foobars base property?

While I already have a workaround for this, I'm trying to understand why this doesn't work. I'm using the grunt-connect-proxy middleware to proxy '/api', and this is my connect task setup (just the relevant code, the rest is set up properly, I promise):

The following does not work, and hitting my dev URL at 0.0.0.0:4000 gives me a "Cannot GET /" message.

livereload: {
  options: {
    middleware: function(connect) {
      return [
        proxySnippet
      ];
    },
    base: [
      '.tmp',
      '<%= yeoman.app %>'
    ]
  }
}

The following does work, which is great. I'm trying to understand why one works and the other doesn't, as the first example reads much nicer, and makes more sense to me.

livereload: {
  options: {
    middleware: function(connect) {
      return [
        proxySnippet,
        connect.static('.tmp'),
        connect.static('<%= yeoman.app %>')
      ];
    }
  },
}

Any insights?

Livereload snippet injection - https support

I have grunt-contrib-connect set up to run with https, which is all working fine - however, using the livereload option, it appears that the snippet that is injected on to the page is still loading over http, causing an error in chrome:

[blocked] The page at 'https://localhost:8001/' was loaded over HTTPS, but ran insecure content from 'http://localhost: 35729/livereload.js?snipver=1': this content should also be loaded over HTTPS.

Is there a way to have the snippet url use https also, if the connect task specifies https?

My connect config:

connect: {
        dev: {
            options: {
                port: '<%= port %>',
                protocol: 'https',
                key: grunt.file.read( sslKeyPath ).toString(),
                cert: grunt.file.read( sslCertPath ).toString(),
                ca: grunt.file.read( sslCsrPath ).toString(),
                passphrase: '<%= sslPassphrase %>',
                hostname: null,
                base: '<%= clientTempPath %>',
                livereload: '<%= livereloadPort %>'
            }
        }
    }

I'm using v0.5.0 of grunt-contrib-connect.

Priority in base array folders doesn't exists

I have this issue here: livedata/grunt-devcode#6
I have an index.js in the .tmp folder and a index.js in the app folder.
It always loads the .tmp/index.js.

My config:

     livereload: {
        options: {
            open: false,
            base: [
                yeomanConfig.app,
                '.tmp'
            ]
        }
    },

I've also tried to change the order of the base, but no luck.

The code that might need changes is:
https://github.com/gruntjs/grunt-contrib-connect/blob/master/tasks/connect.js

I don't know if this is even possible.. thanks
(I don't understand how others can use the grunt-devcode task...)

Allow non-specific hostname binding

The default binding for hostname is "localhost" right now - previously if it was undefined, so you could access the server by any given hostname.

You can get that behavior back by passing undefined as the value for hostname, but I wanted to see about making something official so it's supported. That and you get some fun logging output doing it that way:

Passing an empty string seems to be a better way of doing it, at least as far as output is concerned. With an empty string, the output is

Starting connect web server on :8001.

option to only inject livereload snippet in specified files

I'm testing polymer components, which are loaded into the page with

<link rel="import" href="the-graph-editor.html">

The html imports don't need the livereload snippet, only index.html does. Can there be an option to whitelist which files get the snippet injected?

more flexible config

Right now configuration is not flexible, would be good to be able to declare several server config or even rename the task to server for example, without having to for your own task.

The change below would let you configure like this:

    connect: {
      dev: {
        port: 3010,
        base: 'app/public',
        keepalive: true
      },
      dist: {
        port: 3011,
        base: 'dist/public',
        keepalive: true
      }
    },
var config = target ? grunt.config(['connect' , target]) : grunt.config('connect');
var options = grunt.util._.defaults(config, {

The change below would let you change the task name (maybe there is a better way)

var config = grunt.config([grunt.task.current.name].concat(grunt.task.current.args));
var options = grunt.util._.defaults(config, {

livereload in watch not working

Am I correct in thinking that grunt-contrib-connect should automatically start a local server when livereload is set to true and 'grunt watch' is running? If so, I'm not sure it's working. Though, it's possible I've done something wrong in my Gruntfile (below). Any help would be appreciated.

module.exports = function(grunt) {

grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),

  connect: {
    server: {
      options: {
        // keepalive: true
      }
    }
  },

  compass: {
    dist: {
      options: {
        sassDir: ['stylesheets/sass'],
        cssDir: ['stylesheets'],
      }
    }
  },

  coffee: {
    compile: {
      files: {
        'javascripts/main.js': ['javascripts/coffee/*.coffee'] // compile and concat into single file
      }
    }
  },

  watch: {

    options: {
      livereload: true
    },

    stylesheets: {
      files: ['stylesheets/sass/*.{scss,sass}'],
      tasks: ['compass'],
    },

    javascripts: {
      files: ['**/*.coffee'],
      tasks: ['coffee']
    }

  }

});

grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');

grunt.registerTask('default', ['connect', 'compass', 'coffee', 'watch']);

}

Add livereload option?

Since livereload is now built into the watch task, would it be a good idea to add a tandem livereload option here that configures connect-livereload? It seems it would reduce the config in many gruntfiles that prefer the middleware route for livereload.

I'm happy to submit this addition, LMK! Thanks!

40kb limit on html files

When using grunt server, files with the text/html mimetype only load the first 40960 bytes.

Not sure if this is something that can be changed via connect.limit()? I tried to change it with that but I failed miserably.

To reproduce, make an html file larger than 40kb and curl it or view it in your browser.

I tried setting this up with just senchalabs connect() and it served the whole file so I assume it's something with grunt or this plugin.

Example:
https://github.com/daspecster/grunt-server-limit-example

Set hostname aliases (MAMP Pro like)

As someone who has used MAMP Pro in the past I was spoiled by the ability to have multiple sites running at the same time in their own cool .dev URL's, e.g. http://example.dev/

I think it'd be very cool if we could have the same feature available, not just the cool URL but the ability to have multiple projects running at the same time โ€” although this may already be possible through multiple terminal windows, I'm just getting started so I'm not entirely familiar.

What do you think?

keepalive and executes tasks

The docs say that when using 'keepalive' any other task will never be run.

I think that it would be useful to give the possibility to run tasks with keepalive, as now I use a watch task to keep the server live but every time a file changes grunt print an error about another server instance already active, it works fine but it's quite annoying.

Think about a web app that gets recompiled every time a files change: i want to rebuild the webapp and keep serving it in the browser

TypeError: Object ... has no method 'charAt'

I'm using www.cabinjs.com which uses grunt-contrib-connect.

I'm writing a separate grunt task which I need to run some commands (e.g. git status) but I'm getting an error (which has been raised before in the issues): TypeError: Object ls has no method 'charAt'

My grunt task is...

grunt.registerTask('x', 'y', function(){
    grunt.util.spawn({
        cmd:  ['ls'],
        args: ['-la']
    },
    function (error, result, code) {
        grunt.log.write(error);
        grunt.log.write(result);
        grunt.log.write(code);
    });
  });

...there are separate tasks provided in the Gruntfile for CabinJS and the error happens on the line that calls 'connect' task.

Ideas on how I can resolve this issue and what's causing it?

Thanks

hostname : '*' results in "Fatal error: getaddrinfo ENOTFOUND"

I want the server to listen on all IPs the host has. The grunt config is:

connect : {
unit : {
options : {
hostname : '*',
port : 8078,
base : 'hosts/unit'
}
}
}

When I run grunt connect:unit:keepalive i get the following:

...
Running tasks: connect:unit:keepalive

Running "connect:unit:keepalive" (connect) task
Verifying property connect.unit exists in config...OK
File: [no files]
Starting connect web server on *:8078.
Waiting forever...
Fatal error: getaddrinfo ENOTFOUND

grunt-contrib-connect : 0.2.0
node : 0.8.20

PS. If I remove hostname option everything works on "localhost".

When https: true, livereload snippet not linked properly

When https is set to true, the following snippet is inserted:

<script src="https://0.0.0.0:35729/livereload.js?snipver=1" type="text/javascript">

However, the file does not exist on the https protocol. It exists on the http protocol.

Directory option

It doesn't really make sense to add multiple directory middlewares as you can only browse one. (right?).

It should just pick the base string or the first array item.

I would also like a way to override it. My usecase is that in Yeoman we have a temporary folder with files we want to have override the default ones. So we have the following:

base: [
  '.tmp',
  'app'
]

The problem with that is that the index.html is in the /app folder, not .tmp and index.html won't be shown automatically if you go to http://localhost/

Or would it make sense to have directory be the last array item? That would make my life easier.

@shama

Working with cookies

What is the guideline or recommended setup for debugging cookies with grunt-contrib-connect? Cookies are usually not being set on localhost.

That being said, I'm on a Windows machine, and I would appreciate a different solution than having to modify my hosts file. Thanks.

Options set in Gruntfile.js not honored

Default settings always apply, they are never retrieved from Gruntfile.js

// Handy little development server
server: {
port: 8001,
base: './public'
}

Still loads at port 8000 and current directory.

Can't make config options work.

Can't make provided config to work.
Am I doing something wrong?
Here's my config:

connect: {

    test: {

        base: 'Test Files',
        keepalive: true,
        port: '?'
    }
},

Here's the log from grunt in verbose mode:

Running "connect" task

Running "connect:test" (connect) task
Verifying property connect.test exists in config...OK
File: [no files]
Started connect web server on localhost:8000.

Of all the options only keepalive seems to work.

Add logger as option, not only --debug

How do you like the idea to add logger as option, not only if grunt run with --debug option?

connect: {
    server: {
        options: {
            port: 9001,
            base: 'app',
            logger: 'dev',
            middleware: function(connect, options) {
                var config = [
                    // Serve static files.
                    connect.static(options.base),
                    // Make empty directories browsable.
                    connect.directory(options.base)
                ];

                if (options.logger) {
                    config.unshift(connect.logger(options.logger));
                }

                return config;
            }
        }
    }
},

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.