0

I am using Gulp Angular2 with route

 @RouteConfig([{path:'/contacts', name:'Contacts', component:ContactListComponent, useAsDefault: true    }, {path:'/newcontact', name: 'NewContact', component:NewContactComponent}])

Included base <base href="/"> in HTML.

Below is my gulpfile details

gulp.task('serve', function(){
gulp.watch([config.allTs],['ts-lint','compile-ts']);

browserSync({
    port: 3000,
    files: ['index.html','**/*.js'],
    injectChanges: true,
    logFileChanges: false,
    logLevel: 'silent',
    notify: true,
    reloadDelay: 0,
    server:{
        baseDir: ['./'],
        middleware: superstatic({ debug: false })
        }
});

});

While reloading the page after any change in the ts files, I am getting "Cannot GET /contacts". How to resolve this issue in angular2?

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
Kishore Kumar
  • 21,449
  • 13
  • 81
  • 113

2 Answers2

1

I didn't use superstatic as middleware, but seams like the problem is there. Try using this function as middleware:

var fs = require('fs');
var url = require('url');

function(req, res, next) {
  var fileName    = url.parse(req.url);
      fileName    = fileName.href.split(fileName.search).join('');
  var fileExists  = fs.existsSync(path.resolve(__dirname, './') + fileName);

  if(!fileExists && fileName.indexOf("browser-sync-client") < 0) {
    req.url = "/index.html";
  }
  return next();
}

it will serve index.html if it can't find file for requested path...

Sasxa
  • 40,334
  • 16
  • 88
  • 102
1

In fact, it's normal that you have a 404 error when uploading your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

If you want not having a 404 error, you need to update your server to serve the index.html file for each route path. See the Saxsa's answer for this.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, Location, HashLocationStrategy } from 'angular2/router'; 

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again.

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • HashLocationStrategry is working. But normally it should be without the # bang approach. But when I tried with the PathLocationStrategy mentioned in the documentation I am getting the same error. I will stick with the #bang for this time and waiting for the PathLocationStrategy. – Kishore Kumar Feb 24 '16 at 16:07