How to tell gulp-connect to open index.html regardless of the URL?

All we need is an easy explanation of the problem, so here it is.

I have the following gulp task:

gulp.task('connect', function() {
  connect.server({
    root: __dirname,
    livereload: true
  });
});

and the following Angular routes:

angular.module("MyApp", ["ngRoute"]).config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);

  $routeProvider
    .when("/", {
      controller: "DashboardCtrl",
      templateUrl: "templates/dashboard.html"
    })
    .when("/advertiser", {
      controller: "AdvertiserCtrl",
      templateUrl: "templates/advertiser.html"
    })
    .otherwise({
      redirectTo: "/"
    });
});

When I visit / all works fine (the Dashboard appears).

But, visiting /advertiser results in “404 – Cannot GET /advertiser”.

My main Angular file is index.html, which is opened properly for /, but not for /advertiser.

How could I tell Gulp to open index.html regardless of the URL?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Alternatively you can use gulp-connect own option called fallback for that:

gulp.task('connect', function() {
  connect.server({
    root: 'path/',
    livereload: true,
    fallback: 'path/index.html'
  });
});

No need for another package.

Method 2

You can use the middleware option to use the connect-history-api-fallback middleware. Once you’ve installed and required the fallback, you add it like this:

gulp.task('connect', function() {
  connect.server({
    root: __dirname,
    livereload: true,

    middleware: function(connect, opt) {
      return [ historyApiFallback ];
    }

  });
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply