Angular2 with routing when reloading the page gives Cannot GET?

左心房为你撑大大i 提交于 2019-12-25 01:09:19

问题


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?


回答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...




回答2:


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.



来源:https://stackoverflow.com/questions/35530125/angular2-with-routing-when-reloading-the-page-gives-cannot-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!