刷新页面得到404:仅在使用/dist文件夹时发生 [英] Refresh page got 404: only happen when using /dist folder

查看:364
本文介绍了刷新页面得到404:仅在使用/dist文件夹时发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行在localhost:3000上的LoopBackJS Restful服务器.

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

在前端,我有一个简单的Angular 2应用程序,使用了上述API.

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

在以下情况下一切正常:

Everything is working fine when:

  • 使用nodemon运行服务器(位于my-service/api的根文件夹)
  • 使用npm开始运行客户端(位于my-service/client的根文件夹)

我可以使用localhost:4200来访问我的应用,该应用使用了如上所述在localhost:3000上运行的API.

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

现在,我使用'ng build --prod'构建了Angular应用,并在服务器目录(my-service/api/dist)中指向了输出'dist'文件夹.我已经配置了服务器代码以这种方式工作.

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.

接下来,我使用 http://localhost:3000 访问了我的应用程序,因为现在所有内容都是静态文件.只有在不刷新浏览器的情况下,一切似乎都可以正常工作.错误:

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:

错误 404无法获取/lics 状态:404 错误:无法获取/lics 在raiseUrlNotFoundError

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

发生了什么事,我该如何解决?谢谢.

What happened and how do I fix this? Thanks.

推荐答案

Angular2(现在仅称为Angular)默认使用HTML5历史记录API.加载Angular后,所有URL更改将由Angular处理,并且不会发送到服务器.现在,例如,当您导航到localhost:3000/people/1时,一切正常,因为Angular负责路由.

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.

重新加载页面会将请求发送到服务器.您的服务器不知道people/1,并且将返回404.为了解决此问题,您必须将Angular处理的所有URL重定向到index.html.您的服务器将使用Angular交付index.html而不是404.此时,Angular将再次处理您的路线.

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.

此npm软件包可以帮助您 https://www.npmjs .com/package/express-history-api-fallback

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

在使用npm start开发期间可以正常工作的原因是,Angular CLI使用的webpack开发服务器正在处理重定向.

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.

这篇关于刷新页面得到404:仅在使用/dist文件夹时发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆