Example #1
0
  it("Can still proxy empty requests if the request stream has ended.", function(done) {
    var destServer = createServerWithLibName('http', function(req, resp) {
      resp.statusCode = 200;
      resp.write(req.url);
      resp.end();
    });

    var app = connect();
    //connect.directory causes the incoming request stream to be ended for GETs.
    app.use(connect.directory(path.resolve('.')));
    app.use('/foo', proxy(url.parse('http://localhost:8001/')));

    destServer.listen(8001, 'localhost', function() {
      app.listen(8000);
      http.get('http://localhost:8000/foo/test/', function(res) {
        var data = '';
        res.on('data', function (chunk) {
          data += chunk;
        });
        res.on('end', function () {
          assert.strictEqual(data, '/test/');
          destServer.close();
          done();
        });
      }).on('error', function () {
        assert.fail('Request proxy failed');
      });
    });
  });
  grunt.registerMultiTask('webpack_server', 'Fire up a webpack dev server.', function() {
    var done = this.async();
    var options = this.options({
      entry: './index.js',
      output: {
        path: '/',
      },
      port: 8000,
      keepalive: false,
    });
    var keepAlive = this.flags.keepalive || options.keepalive;
    var base = path.dirname(options.entry);
    var app = connect()
      .use(connect.directory(base))
      .use(connect.static(base))
      .use(middleware(webpack(options, function(err, stats) {
        // TODO: This logs twice for some reason?
        if (!keepAlive) {
          done();
        }
      })));

    // if index.html doesnt exist
    if (!grunt.file.exists(path.join(base, 'index.html'))) {
      app.use(function(req, res) {
        if (req.url === '/index.html') {
          res.end('<html><head><script src="bundle.js"></script></head><body></body></html>');
        }
      });
    }

    app.listen(options.port);
  });
Example #3
0
 return function () {
   var middleware = o.middleware ? o.middleware.call(this, connect, o) : [];
   if (o.livereload) {
     if (typeof o.livereload == 'boolean') o.livereload = {};
     if (!o.livereload.port) o.livereload.port = 35729;
     middleware.push(liveReload({port: o.livereload.port}));
     util.log(util.colors.green('Connect LiveReload on ' + o.livereload.port + ' port'));
   }
   o.root.forEach(function (path) {
     middleware.push(connect.static(path));
   });
   var app = connect.apply(null, middleware);
   var server = http.createServer(app);
   if (o.root.length) app.use(connect.directory(o.root[0]));
   server
     .listen(o.port)
     .on('listening', function () {
       if (o.livereload) {
         lr = tiny_lr();
         lr.listen(o.livereload.port);
       }
       var url, browsername;
       util.log(util.colors.green('Server started on ' + o.port + ' port'));
       if (o.open) {
         url = 'http://localhost:' + o.port + '/' + o.open.file;
         if (o.open.browser) browsername = o.open.browser;
         else browsername = 'default browser';
         open(url, o.open.browser, function (error) {
           if (error) util.log(util.colors.red(error));
           else util.log(util.colors.green('Opened ' + url + ' in ' + browsername));
         });
       }
     })
 };
Example #4
0
module.exports = exports = function initServer( path, opts, callback ){
	opts = opts || {};

    var app = connect();

    if ( opts.verbose ){
		app.use(connect.logger('dev'));
    }


    app
		.use(connect.static( path ))
		.use(connect.directory( path ))
		.use(function( req, res){
			res.statusCode = 404;
			res.end('Error 404: Page does not exist');
		});



    //kick-off starting a server
    exports.tryToMakeServer( app, opts, callback );
	//add your own middleware on app w/ app.use
	return app;
};
Example #5
0
  it("can proxy just the given route.", function(done) {
    var destServer = createServerWithLibName('http', function(req, resp) {
      resp.statusCode = 200;
      resp.write(req.url);
      resp.end();
    });

    var proxyOptions = url.parse('http://localhost:8003/');
    proxyOptions.route = '/foo';

    var app = connect(
      connect.directory(path.resolve('.')),
      // we must pass the route within the options here
      proxy(proxyOptions)
    );

    destServer.listen(8003, 'localhost', function() {
      app.listen(8002);
      http.get('http://localhost:8002/foo/test/', function(res) {
        var data = '';
        res.on('data', function (chunk) {
          data += chunk;
        });
        res.on('end', function () {
          assert.strictEqual(data, '/test/');
          destServer.close();
          done();
        });
      }).on('error', function () {
        assert.fail('Request proxy failed');
      });
    });
  });
Example #6
0
gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'))
        .use('/api-docs', connect.static('api-docs'))
        .use('/api-docs', connect.directory('api-docs'));

    require('http').createServer(app)
        .listen(8000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:8000');
        });
});
gulp.task('server', ['build'], function() {

  var middleware = [
    require('connect-livereload')({ port: lrConfig.port }),
    connect.static(serverConfig.dist),
    connect.directory(serverConfig.dist)
  ];

  var app = connect.apply(null, middleware),
      server = http.createServer(app);

  server
    .listen(serverConfig.port)
    .on('listening', function() {

        gulp.start('watch');

        console.log('Started connect web server on http://localhost:' + serverConfig.port + '.');
        openurl('http://localhost:' + serverConfig.port);
    });

  lrServer.listen(lrConfig.port, function(err) {
    if(err) {
      return console.log(err);
    }
  });
});
Example #8
0
gulp.task('test-server', function() {

  // Open Test Page
  var connect = require('connect');
  var app = connect()
    .use(require('connect-livereload')({port: 35729}))
    .use(connect.static('test'))
    .use('/app', connect.static('app'))
    .use('/bower_components', connect.static('bower_components'))
    .use(connect.directory('test'));

  require('http').createServer(app)
    .listen(8000)
    .on('listening', function () {
      console.log('Started connect testing server on http://localhost:8000');
    });

  require('opn')('http://localhost:8000');

  // Watch for changes in either the test/spec folder or app/scripts folder
  $.livereload.listen();

  gulp.watch([
    'app/scripts/**/*.js',
    'test/spec/**/*.js'
  ]).on('change', $.livereload.changed);

});
Example #9
0
gulp.task('server', function() {

	var app = connect()
				.use(connect.static(path.resolve('.')))
				.use(connect.directory(path.resolve('.')));

	http.createServer(app).listen(9000);

	server.listen(35729, function(err) {
		if(err) return console.log(err);
	});

	gulp.watch('./*.html', function() {
		gulp.src('./*.html')
			.pipe(livereload(server));
	});

	gulp.watch('./js/*.js', function() {
		gulp.run('jshint');
	});	gulp.watch('./sass/*.scss', function() {
		gulp.run('sass');
	});

	gulp.watch('./sass/*.scss', function() {
		gulp.run('sass');
	});

	gulp.run('jshint', 'sass');
});
Example #10
0
	grunt.registerTask('server', 'Start a static web server.', function() {
		// Get values from config, or use defaults.
		var port = grunt.config('server.port') || 8000;
		var base = path.resolve(grunt.config('server.base') || '.');

		var proxy = new httpProxy.RoutingProxy({changeOrigin: true});

		var middleware = [

			//if /api/ called proxying to API
			function(req, res, next){
				var requestedPath = url.parse(req.url).pathname;
				if(requestedPath.indexOf("/api/") == 0){
					proxy.proxyRequest(req, res, {
						host: "weheartpics.com",
						port: 80
					});
					return false;
				}else{
					return next();
				}
			},

			// if request points to non existing file, route to index.html
			function(req, res, next){
				var requestedPath = url.parse(req.url).pathname;
				fs.exists(base + requestedPath, function(exists){
					if(exists){
						return next();
					}else{
						fs.readFile(base + "/index.html", function(error, content){
							if(error){
								console.log("Cannot read file: " + base + "/index.html");
							}else{
								res.writeHead(200, { 'Content-Type': 'text/html' });
								res.end(content, "utf-8");
							}
						});
					}
				});
			},
			
			// Serve other files static
			connect.static(base),
			
			// Make empty directories browsable. (overkill?)
			connect.directory(base)
		];

		// If --debug was specified, enable logging.
		if (grunt.option('debug')) {
			connect.logger.format('grunt', ('[D] server :method :url :status ' +
				':res[content-length] - :response-time ms').magenta);
			middleware.unshift(connect.logger('grunt'));
		}

		// Start server.
		grunt.log.writeln('Starting static web server on port ' + port + '.');
		connect.apply(null, middleware).listen(port);
	});
Example #11
0
  this.start = function(callback){

    var default_root = (common.os_name === 'windows') ? "C:\\"
                       : common.os_name == 'mac' ? '/Users' : '/home';

    var root_path = this.options.root_path || default_root;

    var directory_options = {
      hidden: this.options.show_hidden || false,
      icons: this.options.show_icons || true
    };

    var app = connect()
              .use(connect.logger())
              .use(connect.directory(root_path, directory_options))
              .use(connect.static(root_path));

    var returned = false,
        opened   = false;

    var done = function(err) {
      if (returned) return;
      returned = true;

      if (!opened)
        callback(err || new Error('Unable to connect.'))
      else
        callback(err, self);
    }

    this.server = app.listen(function(err) {
      if (err) return done(err);

      var server = this;

      var local_port = server.address().port;
      common.logger.info('Filebrowser server listening on port' + local_port);

      self.tunnel = new Tunnel({
        local_port  : local_port, 
        remote_host : self.tunnel_host, 
        remote_port : self.tunnel_port
      });

      self.tunnel.on('opened', function(){
        common.logger.info('Tunnel is open!');
        done();
      });

      self.tunnel.on('closed', function(err){
        common.logger.info('Tunnel closed!');
        done(err);
        self.stop(err);
      });

      self.tunnel.open()
    });

  };
gulp.task('serve', function(){
  var app = connect()
    .use(connect.logger('dev'))
    .use(connect.static('./'))
    .use(connect.directory('./'))

  http.createServer(app).listen("8001");
});
Example #13
0
		grunt.util._.each(options.bases, function(b) {
			middleware = middleware.concat([
				// Serve static files.
				connect.static(b),
				// Make empty directories browsable.
				connect.directory(b)
			]);
		});
Example #14
0
gulp.task('webserver', function() {
  var app, base, directory, hostname, port;
  port = 8000;
  hostname = null;
  base = path.resolve('./app');
  directory = path.resolve('./app');
  app = connect().use(connect["static"](base)).use(connect.directory(directory));
  return http.createServer(app).listen(port, hostname);
});
Example #15
0
 grunt.registerTask('server', 'Demo server w/ Ensemble Video "proxying".', function() {
     var port = 8000,
         base = path.resolve('.');
     grunt.log.writeln('Starting ssl web server in "' + base + '" on port ' + port + '.');
     var app = connect()
     // .use(connect.logger())
     .use(connect.urlencoded())
     .use(connect.cookieParser())
     .use(connect['static'](base))
     .use(connect.directory(base))
     .use(function(req, res) {
         var parsed = url.parse(req.url, true);
         // Proxy for EV API requests
         if (parsed.pathname === settings.proxyPath) {
             var ensembleUrl = parsed.query.ensembleUrl,
                 apiUrl = parsed.query.request,
                 username = req.cookies[encodeURIComponent(ensembleUrl) + '-user'],
                 password = req.cookies[encodeURIComponent(ensembleUrl) + '-pass'];
             if (apiUrl) {
                 var opts = {
                     url: apiUrl,
                     strictSSL: false
                 };
                 if (username && password) {
                     _.extend(opts, {
                         auth: {
                             username: username,
                             password: password
                         }
                     });
                 }
                 var r = request.get(opts);
                 r.pipefilter = function(response, dest) {
                     dest.removeHeader('www-authenticate');
                 };
                 r.pipe(res);
             } else {
                 res.statusCode = 400;
                 res.end("Missing request parameter.");
             }
         }
         // LTI demo launch path
         else if (parsed.pathname === '/demo/lti/launch' && req.method === 'POST') {
             console.log(req);
             var returnUrl = req.body.launch_presentation_return_url;
             // We're just doing a simple redirect here
             res.writeHead(302, {
                 'Location': 'https://' + req.headers['host'] + '/demo/lti/index.html?return_url=' + encodeURIComponent(returnUrl)
             });
             res.end();
         }
     });
     https.createServer({
         key: fs.readFileSync('assets/ssl/certs/ev-script-key.pem'),
         cert: fs.readFileSync('assets/ssl/certs/ev-script-cert.pem')
     }, app).listen(port);
 });
 addDirectory: function (app, base, directory) {
     var dirBase = base;
     if (directory) {
         if (typeof directory === "string") {
             dirBase = filePath.resolve(directory);
         }
         app.use(connect.directory(dirBase, {icons:true}));
     }
 }
Example #17
0
  function createStaticServer(rootname) {
    var app
      , server
      , failed = false
      , somereq
      ;

   function useUserReq(req, res, next) {
      try {
        somereq(req, res, next);
      } catch(e) {
        if (!failed) {
          console.error("required '" + rootname  + "', but couldn't use it as a connect module");
          console.error(e);
          failed = true;
        }
        next();
      }
    }

    app = connect();

    try {
      somereq = require(rootname);

      if ('function' === typeof somereq) {
        app.use(useUserReq);
      } else {
        app.use(somereq);
      }

      console.log(rootname, "is a loadable module. I'm gonna load it!");
    } catch(e) {
      console.log(rootname, "is not a loadable module and that's okay.");
      // ignore
    }

    app
      .use(connect.static(rootname))
      .use(connect.directory(rootname))
      .use(createFileReceiver(rootname))
      .use('/version', function (req, res, next) {
          res.end(version);
        })
      .use(connect.json())
      .use(connect.urlencoded())
      .use(connect.multipart())
      .use(function (req, res) {
          console.log(req.body);
          res.end();
        })
      ;

    return app;
  }
Example #18
0
gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(9000)
});
Example #19
0
module.exports = function(options, callback) {
    var app = connect();
    if(options.local){
        app.use("/" + options.local,connect.static(cwd));
        app.use("/" + options.local,connect.directory(cwd));   
    }
    app.use(SERVER_PATH, connect.static(SERVER_ROOT));
    app.use(SERVER_PATH, connect.directory(SERVER_ROOT));

    app.listen(options.port, function() {
        var url = 'http://localhost:' + options.port + SERVER_PATH;

        logger.info( logger.template(MESSAGE.SERVER_STARTED, {
            url: url
        }) );

        options.open && require('child_process').exec('open ' + url);
        callback && callback()
    });
};
Example #20
0
gulp.task('webserver', function () {
    var port = 3000,
        hostname = null,
        base = path.resolve('.'),
        directory = path.resolve('.');

    var app = connect()
        .use(connect.static(base))
        .use(connect.directory(directory));

    http.createServer(app).listen(port, hostname);
});
Example #21
0
gulp.task('connect-dist', ['dist'], function() {
    var connect = require('connect');
    var app = connect()
        .use(connect.static('dist'))
        .use(connect.directory('dist'));

    runningServer = require('http').createServer(app);
    runningServer.listen(8001)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:8001');
        });
});
Example #22
0
gulp.task('connect', function () {
    var connect = require('connect');
    connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'))
        .listen(9000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:9000');
        });
});
Example #23
0
function startTestScriptServer(config) {
    var app = connect()
        .use(connect.static(config.testScriptServer.appDir))
        .use(connect.directory(config.testScriptServer.appDir));

    http.createServer(app)
        .listen(config.testScriptServer.port)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:' + config.testScriptServer.port + '.');
            runTests(config);
        });
}
Example #24
0
gulp.task('connect:dist', ['build'], function () {
    var connect = require('connect');
    var app = connect()
        .use(connect.static('dist'))
        .use(connect.directory('dist'));

    require('http').createServer(app)
        .listen(3002)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:3002');
        });
});
Example #25
0
 async.series([loadConfig, cacheConfig], function() {
   var app = connect().
       use(manageConfigCache).
       use(getInfoJson).
       use(connect.query()).
       use(proxyModule).
       use(addModule).
       use(beautify).
       use(connect.static(fileDir, {'maxAge': 200 * 1000})).
       use(connect.directory(fileDir)).
       use(connect.errorHandler()).
       listen(argv.port);
 });
Example #26
0
gulp.task('serve-dist-without-build', [], function() {
    var connect = require('connect');
    var app = connect()
        .use(connect.static('dist'))
        .use(connect.directory('dist'));

    require('http').createServer(app)
        .listen(8001)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:8001');
            require('opn')('http://localhost:8001');
        });
})
Example #27
0
    grunt.registerTask('runserver', 'Start the development server.', function(port) {
        this.async();
        port = port || 8000;

        connect()
            .use(connect.static('src'))
            .use(connect.directory('src', {icons: true}))
            .use('/js/vendor', connect.static('bower_components'))
            .use('/js/vendor', connect.directory('bower_components', {icons: true}))
            .use(connect.logger())
            .listen(port)
            .on('listening', function() {
                grunt.log.writeln('Starting static web server on port ' + port + '.');
            })
            .on('error', function(err) {
                if (err.code === 'EADDRINUSE') {
                    grunt.fatal('Port ' + port + ' is already in use by another process.');
                } else {
                    grunt.fatal(err);
                }
            });
    });
Example #28
0
gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(9000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:9000');
        });
});
Example #29
0
gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static(config.app))
        .use(connect.directory(config.app));

    require('http').createServer(app)
        .listen(config.port)
        .on('listening', function() {
            console.log('Started connect web server on http://localhost:' + config.port + '.');
        });
});
function connectAddOptions(app, httpType) {
	app.use("/", function(req, res) {
		getRequestResponse(req, res, httpType + "Connect");
	});

	app.use(connect.static(__dirname + FILEDIR));

/* OPTIONAL ADDONS */
//	app.use(connect.favicon());
//	app.use(connect.logger('dev'));
	app.use(connect.directory(__dirname + FILEDIR));
//	app.use(connect.cookieParser());

}