2016-01-14 33 views
0

我使用模塊化的路線,我想從我的URL中刪除#標記。然而,大多數的文章說,我將此代碼添加到我的路線locationProvider html5mode不工作

.config(function ($routeProvider, $locationProvider) { 
$routeProvider 
    .otherwise({ 
    redirectTo: '/' 
    }); 

    // use the HTML5 History API 
    $locationProvider.html5Mode(true); 

}) 

,我已將此添加到我的母版頁(index.html的)

<head> 
<meta charset="utf-8"> 
<title></title> 
<meta name="description" content=""> 
<meta name="viewport" content="width=device-width"> 
<!-- Place favicon.ico and apple-touch-icon.png in the root directory --> 
<!-- build:css(.) styles/vendor.css --> 
<!-- bower:css --> 
<link rel="stylesheet"   href="bower_components/bootstrap/dist/css/bootstrap.css" /> 
<!-- endbower --> 
<!-- endbuild --> 
<!-- build:css(.tmp) styles/main.css --> 
<link rel="stylesheet" href="styles/main.css"> 
<!-- endbuild --> 
<base href="/"> 
</head> 

,我加入的鹼標籤了。但問題是,當我進入這樣

https://localhost:9000/loginselect 

的URL,它說

Cannot GET /loginselect 

但是,如果我進入這個如下(爲previus)其工作

https://localhost:9000/#/loginselect 

,但它顯示該網址爲

https://localhost:9000/loginselect 

但是當我再次刷新發生同樣的錯誤。任何人都可以幫助我。我使用requireJs加載文件和模塊化路由文件正在使用requireJs加載

回答

1

您需要配置您的服務器以在該路徑上提供index.html。

html5Mode只設置Angulars行爲,當涉及到非零碎的url時,但Angular只處理第一個請求之後的事情,因爲在第一個請求頁面時,javascript甚至還沒有加載。第一個請求總是碰到服務器,所以當你直接輸入url https://localhost:9000/loginselect時,一個請求將被髮送到服務器,如果服務器不能識別這個url,你將會得到一個錯誤。

爲了解決這個問題,你需要配置你的服務器來爲你的index.html文件服務器爲你的應用程序使用的URL。通常,您將設置服務器在任何url上發送index.html,除了那些匹配的靜態資產(如圖像)。如果你這樣做,那麼在這些URL上,服務器將加載index.html,Angular將啓動,並且Angular將處理該路由。

它適用於https://localhost:9000/#/loginselect的原因是,通過約定,服務器將忽略url的片段部分,即'#/ loginselect`。所以服務器抓住/ /(因爲它忽略了其餘部分),這可能是index.html。角然後踢和處理片段部分。

編輯:

要在nginx的做到這一點我會使用這樣的:

location/{ 
    index index.html; 
    try_files $uri $uri/ /index.html =404; 
} 

此檢查是否有給(所以如果你問一個靜態的路徑上的一個文件像它會給你的圖像資源),如果它找不到一個它將代替index.html。

請注意,這是最簡單的情況,它具有在任何404上爲index.html提供服務的缺點。您也可以更具體並排除某些目錄(如/ assets或/ static)而不是執行try_files 。然後,如果您嘗試獲取不存在的靜態資產,您仍然可以擁有404。

+0

好的。假設我想直接通過輸入該網址(** https:// localhost:9000/loginselect **)直接進入** https:// localhost:9000/loginselect ** url並按回車。目前它沒有像我說的那樣工作。如果我輸入(** https:// localhost:9000 /#/ loginselect **),它就可以工作。我想直接通過輸入該網址(** https:// localhost:9000/loginselect **)直接進入** https:// localhost:9000/loginselect **網址,然後按回車。你能告訴我如何配置我的服務器嗎? –

+0

這完全取決於您的服務器。我將添加如何在nginx中完成它,不知道其他事情。 –

0

如果你在服務器上運行Apache,你可以把它放在你的。htaccess文件,它應該允許你直接去任何有效的網址。但嚴重的是,我已經在Angular工作了一年多了,現在在一個專業的環境中:沒有人關心網址中的#。離開它比試圖移除它更容易。

<ifModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_URI} !index 
    RewriteCond %{REQUEST_URI} !.*\.(css¦js|html|png) #Add extra extensions needed. 
    RewriteRule (.*) index.html [L] 
</ifModule> 
+0

它可能有SEO的含義(重點可能,我從來沒有正確測試過)。 Google和Bing抓取工具可以使用html5mode讀取頁面,但我不確定他們是否可以不讀取頁面。新的ajax爬行基於pushstates,我不認爲Angular在html5mode不使用時會使用它。另外,我在乎!片段是應該從最終用戶隱藏的實現細節。除非它是一個內部管理員......那我就不會在乎:) –