遇到的問題
帶路由的應用應該支持“深鏈接”。 所謂深鏈接就是指一個 URL,它用於指定到應用內某個組件的路徑。 比如,http://www.mysite.com/heroes/42
就是一個到英雄詳情頁面的深鏈接,用於顯示 id: 42
的英雄。
當用戶從運行中的客戶端應用導航到這個 URL 時,這沒問題。 Angular 路由器會攔截這個 URL,並且把它路由到正確的頁面。
但是,當從郵件中點擊鏈接或在瀏覽器地址欄中輸入它或僅僅在英雄詳情頁刷新下瀏覽器時,所有這些操作都是由瀏覽器本身處理的,在應用的控制範圍之外。 瀏覽器會直接向服務器請求那個 URL,路由器沒機會插手。
靜態服務器會在收到對 http://www.mysite.com/
的請求時返回 index.html
,但是會拒絕對 http://www.mysite.com/heroes/42
的請求, 並返回一個 404 - Not Found
錯誤,除非,它被配置成了返回 index.html
。
解決辦法
第一:從網上下載RewriteModule 並安裝到IIS 模塊中
第二: 在web.config中增加一條重寫規則
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
這樣就可以直接將深鏈接(http://www.mysite.com/heroes/42
)粘貼到瀏覽器上就可以訪問了。
注:如果不生效,可以重置IIS,或者重啓服務器,以便RewriteModule生效