Refresh page got 404: only happen when using /dist

2019-02-26 03:56发布

问题:

I have a LoopBackJS Restful server running at: localhost:3000.

At front-end side, I have a simple Angular 2 app that consumes the above APIs.

Everything is working fine when:

  • Using nodemon to run the server (root folder at my-service/api)
  • Using npm start to run the client side (root folder at my-service/client)

I can do localhost:4200 to access my app which consumes the APIs running at localhost:3000 as mentioned above.

Now I built the Angular app using 'ng build --prod' and pointed the output 'dist' folder inside the server directory (my-service/api/dist). I've configured the server code to work this way.

Next I accessed my app using http://localhost:3000 because everything is static files now. Everything seem to be working only if I don't refresh the browser. The error:

Error 404 Cannot GET /lics status: 404 Error: Cannot GET /lics at raiseUrlNotFoundError

What happened and how do I fix this? Thanks.

回答1:

Angular2 (now just called Angular) is using the HTML5 History API by default. Once Angular is loaded, all URL changes are handled by Angular and are not sent to the server. Now when you navigate to localhost:3000/people/1 for example, everything works fine, since Angular is taking care of the routing.

Reloading the page will send the request to the server. Your server don't know people/1 and will return 404. In order to solve this problem you have to redirect all URLs, which are handled by Angular, to your index.html. Instead of 404 your server will deliver your index.html with Angular. At this point Angular will take care of your routes again.

This npm package could help you with that https://www.npmjs.com/package/express-history-api-fallback

The reason why it works during development with npm start is that webpack dev server, which is used by the Angular CLI, is handling the redirects.