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

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

问题描述

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

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

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

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 start 运行客户端(位于 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 应用程序,并将输出的 'dist' 文件夹指向服务器目录 (my-service/api/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 History 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天全站免登陆