Angular 路由如何优先于静态站点上的文件路径 [英] How does Angular routing take precedence over file paths on a static site

查看:22
本文介绍了Angular 路由如何优先于静态站点上的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用文件结构构建一个静态站点:

-index.html-博客/index.html

我在 blog/index.html 中放置了一个带有路由的 Angular 应用程序,然后转到路由 example.com/blog/page/2,它转到Angular 应用程序中正确的博客页面.从某种意义上说,它打开 /blog/index.html,并在 Angular 应用程序中处理 /page/2.

怎么样?

为什么 Apache(或 Nginx)不优先于它,并尝试打开 /blog/page/2/index.html,但没有找到它,显示 404?

我认为它能像这样工作真是太棒了,但我不知道它在技术上是如何可行的.

解决方案

apache 或 nginx 或任何您的 Web 服务器都需要正确且有意地配置为服务于 Angular 应用程序.对于各种 Web 服务器配置,有无数指南,但通常您会配置任何 404 错误以重定向到项目根 index.html 页面.但是,如果出现 REAL 404,您的 Angular 应用应该设置为正确处理它.

这仅用于初始页面加载或刷新.一旦 angular 应用程序启动并运行,这是一个有争议的问题,因为 angular 会拦截并处理所有导航,因此它不会再次访问您的 Web 服务器.angular router 只是调用它需要的文件,并使用浏览器历史 API 将项目推送到您的网络历史记录中以模拟正常导航.它们被称为单页应用程序,因为实际上您的 Web 服务器只提供一个页面,其余的都是技巧/模拟.

If I build a static site with the file structure:

-index.html
-blog/index.html

And I put an Angular app with routing inside blog/index.html, then go to the route example.com/blog/page/2, it goes to the correct blog page within the Angular application. In a sense, it opens /blog/index.html, and processes /page/2 within the Angular application.

How?

Why doesn't Apache (or Nginx) take precedence over that, and try to open /blog/page/2/index.html, and not finding it, show a 404?

I think it's pretty awesome that it can work like this, but I can't figure out how it's technically possible.

解决方案

apache or nginx or whatever your web server is needs to be properly and intentionally configured to serve an angular app. There are countless guides for various web server configs, but generally you will configure any 404 error to redirect to the project root index.html page. In the event of a REAL 404 however, your angular app should be set up to handle it properly.

This is for initial page load or refresh ONLY. Once the angular app is up and running, it's a moot point because angular intercepts and handles all navigation so it doesn't hit your web server again. The angular router just calls up the files it needs and uses the browser history API to push items into your web history to simulate normal navigation. They're called Single Page Applications because there is actually only a single page ever served from your web server, the rest is all tricks / simulation.

这篇关于Angular 路由如何优先于静态站点上的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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