美文网首页
干净的 angularjs router

干净的 angularjs router

作者: sherlock221b | 来源:发表于2015-10-22 12:59 被阅读187次
Paste_Image.png

angularjs 确实好用, 但是每次访问angular的 资源的时候url 后面总是带个#号让人略显不爽.
<pre>http://localhost:7160/boss/index.html#/auth/login</pre>

以下办法可以教你去除url后面的符号 变成干净整洁的url
以上特性都建立在html5 history上面, 具体参考这个(http://diveintohtml5.info/history.html)
简单来说可以使用javascript修改地址栏路径,而不刷新页面。

<pre>http://localhost:7160/boss/auth/login</pre>

html5mode

$locationProvider --> html5Mode
在 angularjs 中 只需要开启html5Mode的模式 就可以使用这个特性 位置是在路由配置的地方
<pre>
$locationProvider.html5Mode(true)
</pre>

<base>

<pre>
<head>
<base href="/项目名/index.html">
</head>
</pre>

在head中写入base 标签 这里采用根路径定位当前index.html
关于base配置可参考angularjs 官方文档
https://docs.angularjs.org/error/$location/nobase

部署服务器重写

当你发现刷新页面 或者新打开一个url的时候 显示404 这部分是因为url 交给服务端接管了 解决办法 在服务端 检查发现url 来自angular 转发给我们的base即可

服务器端配置

nginx
<pre>
server {
server_name my-app; root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
</pre>

Paste_Image.png

其他服务器请参考如下链接:
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

参考文章 :
http://www.tuicool.com/articles/7NnUFr2

相关文章

网友评论

      本文标题:干净的 angularjs router

      本文链接:https://www.haomeiwen.com/subject/mrjthttx.html