itsource

해시 '#'이 없는 AngularJS 라우팅

mycopycode 2022. 9. 25. 00:24
반응형

해시 '#'이 없는 AngularJS 라우팅

나는 앵글을 배우고 있다.JS와 나를 정말 짜증나게 하는 것이 하나 있다.

용 i i i i를 쓴다.$routeProvider응용 프로그램의 라우팅 규칙을 선언하려면:

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

에서 내 하면 '어플리케이션'이 표시됩니다.app/#/testapp/test.

왜 가 되느냐는 입니다.는 이 해시 JS를 합니다.#URL? 수 있는 요?할할수 능능? 능? ????

실제로 HTML5 이외의 브라우저에는 #(해시태그)가 필요합니다.

그 이외의 경우는, 상기의 href 에 있는 서버에 대해서 HTTP 콜만 실행합니다.#는 요청을 실행하지 않는 오래된 브라우저 단락입니다.이것에 의해, 많은 js 프레임워크가 그 위에 독자적인 클라이언트 사이드 재루팅을 구축할 수 있습니다.

하시면 됩니다.$locationProvider.html5Mode(true)HTML5 를를를 를를를를를 를를를 를를를 를를.

다음은 HTML5 전략을 지원하는 브라우저 목록입니다.http://caniuse.com/ #history = history

를 유효하게 해, 「」를 ,.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 헤드에서 기본 태그 추가

<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-hashtaghttpsscotch.io/quick-tips/

Angular의 URL에서 깨끗한 URL을 얻거나 해시태그를 삭제하는 것은 매우 간단합니다.
로는 Angular by by by by by by by 。JS의 URL.§:

해야 할 일이 두 가지 있습니다.

  • $location Provider 설정

  • 상대 링크 기반 설정

  • $location 서비스

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

상대 링크 설정

  • 링크를 하려면 , 「」를 .<base> <head>를 참조해 주세요.각근인덱스.html의 각근인덱스.:<base>태그를 지정하고 앱에 사용할 루트 URL로 설정합니다.

를 들면, '먹다'와 같이요.<base href="/">

  • 이 설정에는 그 밖에도 여러 가지 방법이 있으며 HTML5 모드를 true로 설정하면 상대 링크가 자동으로 해결됩니다.애플리케이션의 루트가 URL과 다른 경우(예: /my-base) 베이스로 사용합니다.

오래된 브라우저의 폴백

  • $location 서비스는 HTML5 History API를 지원하지 않는 브라우저의 경우 자동으로 해시방 방식으로 폴백됩니다.
  • 이 작업은 사용자에게 투명하게 수행되며 작동하기 위해 아무것도 구성할 필요가 없습니다.Angular $location 문서에서 폴백 방식과 그 구조를 확인할 수 있습니다.

결론적으로

  • 이것은 예쁜 URL을 얻고 Angular 어플리케이션에서 해시태그를 삭제하는 간단한 방법입니다.매우 깨끗하고 빠른 Angular 앱을 즐겨보세요!

HTML5 URL 을 html 。기본적으로 어플리케이션의 엔트리 포인트(index.html 등)에 대한 모든 링크를 다시 써야 합니다.「」의 <base>태그는 또한 이 경우에 중요하다. 왜냐하면 그것은 Angular를 가능하게 하기 때문이다.JS: 응용 프로그램 기반인 URL 부분과 응용 프로그램에서 처리해야 하는 경로를 구분합니다.자세한 내용은 각도를 참조하십시오.JS 개발자 가이드 - $location HTML5 모드 서버 측 사용.


갱신하다

방법: html5Mode와1 연동하도록 서버를 설정합니다.

html5Mode를 이노블로 하면#문자는 URL에서 더 이상 사용되지 않습니다.#심볼은 서버측 설정이 필요 없기 때문에 편리합니다.없이.#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

「 」를 참조해 주세요.

Apache를 사용하는 Angular를 사용하는 OS X 10.8에서 로컬로 이 설정을 원하는 경우 .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

rewrite base가 필요합니다.그렇지 않으면 서버 루트에 대한 요구가 해결됩니다.이러한 요구는 vhost를 특별히 설정하지 않는 한 기본적으로는 프로젝트 디렉토리가 아닙니다.따라서 요청이 프로젝트 루트 디렉토리를 찾도록 경로를 설정해야 합니다.예를 들어 내 컴퓨터에는 모든 프로젝트를 보관하는 /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}

**

Angular에서 위치 전략으로 HTML 5 스타일(Path Location Strategy)을 사용하는 것이 좋습니다.

** 왜냐하면

  1. 사용자가 보다 쉽게 이해하고 기억할 수 있는 클린 URL 및 SEO 프렌들리 URL을 생성합니다.
  2. 클라이언트에게 전달하기 전에 먼저 서버의 페이지를 렌더링함으로써 애플리케이션 로드를 고속화할 수 있는 서버측 렌더링을 이용할 수 있습니다.

Hashlocationstrtegy는 오래된 브라우저를 지원해야 하는 경우에만 사용하십시오.

자세한 내용은 여기를 클릭해 주세요.

언급URL : https://stackoverflow.com/questions/14319967/angularjs-routing-without-the-hash

반응형