簡體   English   中英

沒有哈希'#'的AngularJS路由

[英]AngularJS routing without the hash '#'

我正在學習 AngularJS,但有一件事讓我很惱火。

我使用$routeProvider為我的應用程序聲明路由規則:

$routeProvider.when('/test', {
  controller: TestCtrl,
  templateUrl: 'views/test.html'
})
.otherwise({ redirectTo: '/test' });

但是當我在瀏覽器中導航到我的應用程序時,我看到app/#/test而不是app/test

所以我的問題是為什么 AngularJS 將這個哈希#添加到 urls 中? 有沒有可能避免它?

事實上,對於非 HTML5 瀏覽器,您需要 #(hashtag)。

否則,他們只會在提到的 href 處對服務器進行 HTTP 調用。 # 是一個舊的瀏覽器短路,它不會觸發請求,它允許許多 js 框架在此基礎上構建自己的客戶端重新路由。

如果可用,您可以使用$locationProvider.html5Mode(true)告訴 angular 使用 HTML5 策略。

以下是支持 HTML5 策略的瀏覽器列表: http : //caniuse.com/#feat=history

如果您像其他人所說的那樣啟用了 html5mode,並創建一個包含以下內容的.htaccess文件(根據您的需要進行調整):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

當用戶輸入正確的路線時,他們將被引導到您的應用程序,您的應用程序將讀取路線並將他們帶到其中的正確“頁面”。

編輯:只要確保沒有任何文件或目錄名稱與您的路由沖突。

讓我們寫一個看起來簡單而簡短的答案

在路由器末尾添加html5Mode(true) ;

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

在 html head 中添加base標簽

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

感謝@plus - 詳細說明上述答案

嘗試

$locationProvider.html5Mode(true)

更多信息請訪問$locationProvider
使用 $location

以下信息來自:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

在 Angular 中獲取干凈的 URL 並從 URL 中刪除主題標簽非常容易。
默認情況下,AngularJS 會路由帶有標簽的 URL 例如:

有兩件事需要做。

  • 配置 $locationProvider

  • 設置我們的相對鏈接基礎

  • $定位服務

在 Angular 中,$location 服務解析地址欄中的 URL 並對您的應用程序進行更改,反之亦然。

我強烈建議通讀官方的 Angular $location 文檔,以了解定位服務及其提供的內容。

https://docs.angularjs.org/api/ng/service/$location

$locationProvider 和 html5Mode

  • 我們將使用 $locationProvider 模塊並將 html5Mode 設置為 true。
  • 我們將在定義 Angular 應用程序和配置路由時執行此操作。

     angular.module('noHash', []) .config(function($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl : 'partials/home.html', controller : mainController }) .when('/about', { templateUrl : 'partials/about.html', controller : mainController }) .when('/contact', { templateUrl : 'partials/contact.html', controller : mainController }); // use the HTML5 History API $locationProvider.html5Mode(true); });

什么是 HTML5 歷史 API? 這是使用腳本操縱瀏覽器歷史記錄的標准化方法。 這讓 Angular 可以在不刷新頁面的情況下更改我們頁面的路由和 URL。 有關這方面的更多信息,這里有一篇很好的 HTML5 History API 文章:

http://diveintohtml5.info/history.html

相對鏈接的設置

  • 要使用相對鏈接圍繞您的應用程序進行鏈接,您需要在文檔的<head>中設置<base> 這可能位於 Angular 應用程序的根 index.html 文件中。 找到<base>標記,並將其設置為您希望用於應用的根 URL。

例如: <base href="/">

  • 還有很多其他方法可以配置它,設置為 true 的 HTML5 模式應該會自動解析相關鏈接。 如果您的應用程序的根目錄與 url 不同(例如 /my-base,則將其用作基礎。

舊瀏覽器的回退

  • 對於不支持 HTML5 History API 的瀏覽器,$location 服務將自動回退到 hashbang 方法。
  • 這對您來說是透明的,您無需對其進行任何配置即可工作。 從 Angular $location 文檔中,您可以看到回退方法及其工作原理。

綜上所述

  • 這是獲取漂亮 URL 並刪除 Angular 應用程序中的主題標簽的簡單方法。 享受制作那些超級干凈和超級快速的 Angular 應用程序的樂趣!

使用 HTML5 模式需要在服務器端重寫 URL,基本上你必須重寫所有指向應用程序入口點的鏈接(例如 index.html)。 需要一個<base>標簽對於這種情況也很重要,因為它允許 AngularJS 區分作為應用程序基礎的 url 部分和應用程序應該處理的路徑。 有關更多信息,請參閱AngularJS 開發人員指南 - 使用 $location HTML5 模式服務器端


更新

如何:配置您的服務器以使用 html5Mode 1

啟用 html5Mode 后,您的網址中將不再使用#字符。 #符號很有用,因為它不需要服務器端配置。 沒有# ,url 看起來更好,但它也需要服務器端重寫。 這里有些例子:

Apache 重寫

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Nginx 重寫

server {
    server_name my-app;

    index index.html;

    root /path/to/app;

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

Azure IIS 重寫

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" 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="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

快速重寫

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use

也可以看看

如果您想在 OS X 10.8 上本地配置它,使用 Apache 服務 Angular,那么您可能會在 .htaccess 文件中找到以下幫助:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteBase /~yourusername/appname/public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
    RewriteRule (.*) index.html [L]
</IfModule>

選項 +FollowSymlinks 如果未設置可能會在日志中給您一個禁止的錯誤,如下所示:

Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden

需要重寫基礎,否則請求將被解析到您的服務器根目錄,默認情況下本地不是您的項目目錄,除非您專門配置了虛擬主機,因此您需要設置路徑,以便請求找到您的項目根目錄。 例如,在我的機器上,我有一個 /Users/me/Sites 目錄,用於保存我所有的項目。 就像舊的 OS X 設置一樣。

接下來的兩行有效地說明了路徑是否不是目錄或文件,因此您需要確保沒有與應用程序路由路徑相同的文件或目錄。

下一個條件表示如果請求未以指定的文件擴展名結尾,則在那里添加您需要的內容

[L] 最后一個是說為 index.html 文件提供服務 - 您的應用程序用於所有其他請求。

如果您仍然有問題,請檢查 apache 日志,它可能會給您有用的提示:

/private/var/log/apache2/error_log

在 Angular 6 中,您可以使用路由器:

RouterModule.forRoot(routes, { useHash: false })

您還可以使用以下代碼重定向到主頁(主頁):

{ path: '', redirectTo: 'home', pathMatch: 'full'}

如上所述指定重定向后,您可以重定向其他頁面,例如:

{ path: 'add-new-registration', component: AddNewRegistrationComponent},
{ path: 'view-registration', component: ViewRegistrationComponent},
{ path: 'home', component: HomeComponent}

**

建議使用 HTML 5 樣式(PathLocationStrategy)作為 Angular 中的定位策略

**因為

  1. 它生成干凈且 SEO 友好的 URL,用戶更容易理解和記住。
  2. 您可以利用服務器端渲染,這將使我們的應用程序加載速度更快,方法是先在服務器中渲染頁面,然后再將其交付給客戶端。

僅當您必須支持舊瀏覽器時才使用 Hashlocationstrtegy。

點擊這里了解更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM