为什么 MEAN.js 个应用程序的 URL 以 #!

Why MEAN.js applications'URL start with #!

我刚刚用 MEAN.JS 开始了我的第一个 MEAN 应用程序构建。在发现 mean.js 如何组织应用程序后,我想知道为什么 URL 以 /#!/.

开头

例如我想要的登录页面:

http://example.com/login

而不是:

http://example.com/#!/login

所以我查看了 Express 和 Angular 文档,但一无所获。我还阅读了完整的 MEAN.JS 文档,但仍然一无所获。

在 Angular 的模块配置路由文件中,URL 没有前缀 #!:

users.client.routes.js:

...
state('login', {
    url: '/login',
    templateUrl: 'modules/users/views/authentication/login.client.view.html'
}).
...

所以我最后有两个问题:

  1. 为什么 URL 这样开头?这背后有什么好的做法吗?
  2. 如果这不是坏事,我可以如何以及在何处更改这些 URL?

Angular 在非 HTML5 浏览器的 url 中使用主题标签。

这可以通过以下方式解决:

angular.module('yourapp').config(function($locationProvider) {
    $locationProvider.html5Mode(true); 
}));

Angular,与所有单页应用程序框架一样,使用散列 # 锚点来欺骗浏览器将客户端链接重定向回 JavaScript,而不是发出服务器请求。 $location service用于管理这个进程。

The $location service parses the URL in the browser address bar (based on window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into the $location service and changes to $location are reflected into the browser address bar.

其他框架使用 hashbang,或 #! 允许您仍然使用 # 作为实际页面锚点。 angular 位置服务可以自定义以启用此功能,如果您的目标受众使用 HTML 5 兼容浏览器,也可以自定义以允许您根本不使用 #,并且您已经在您的服务器上配置了额外的重定向。

Mean.js 开发团队选择启用 hashbang 格式作为他们的标准。在 https://github.com/meanjs/mean/blob/master/public/application.js 你会看到 $locationProvider.hashPrefix('!');

您也可以使用您自己的自定义覆盖它(例如 $ 用于 #$ 路径),删除此行并恢复为默认值 # 而不是 #! 用于 angular,或启用 HTML 5 模式。

最好通读 $location service 的文档,因为它讨论了页面刷新影响、网络爬虫、服务器配置选项、HTML 5 模式的注意事项等。