Angular 2 rc4 can not go to page by typing the url

2019-07-09 03:51发布

问题:

I 've just update my project to version rc 4 and got the problem.

When I use the systemjs to config my project, everything is ok.

When I run the project with webpack (I am using the angular2-webpack-starter ) the project was run successfully, no bugs. I can go to every link which was config by [routerLink].

But with the same link if I type the url to the browser's address bar. There was nothing happened. My app did not load anything. Here is some screen shot from my project:

Screen shot

Can anyone help me? I am thank you so much.

回答1:

This needs to be handled by your back-end server.

You need to send all requests to the index page so that Angular can pick up the request and resolve the route from there.

What's happening is when you visit your index(/) page Angular takes over and when you click on a [routerlink] it pretends to change the page in the browser (it's not actually doing anything with the server). When you visit any page that isn't the index by typing in the URL then you are not loading your Angular app and therefore it's not able to edit routes in the browser. By forwarding all routes to the index we're letting Angular decide how all routes should be handled, instead of the server.



回答2:

Ìf you serve the content by JS. Add this code to express route

var path = require('path')

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname + '/static/index.html'));
});