Reputation: 21863
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?
Upvotes: 0
Views: 1454
Reputation: 202176
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.
Upvotes: 1
Reputation: 41264
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...
Upvotes: 1