[angular] 브라우저를 다시로드 할 때 Angular 2.0 라우터가 작동하지 않습니다

Angular 2.0.0-alpha.30 버전을 사용하고 있습니다. 다른 경로로 리디렉션하면 브라우저를 새로 고침하여 GET / 라우트 할 수 없음을 표시합니다.

이 오류가 발생한 이유를 알아낼 수 있습니까?



답변

당신이보고있는 오류는 존재하지 않는 http : // localhost / route를 요청하기 때문입니다. 사이먼 에 따르면 .

html5 라우팅을 사용하는 경우 앱의 모든 경로 (현재 404)를 서버 측의 index.html매핑 해야합니다 . 다음은 몇 가지 옵션입니다.

  1. 라이브 서버 사용 : https://www.npmjs.com/package/live-server

    $live-server --entry-file=index.html`
    
  2. nginx 사용 : http://nginx.org/en/docs/beginners_guide.html

    error_page 404 /index.html
    
  3. Tomcat-web.xml 구성 에서 Kunin 의 코멘트

    <error-page>
          <error-code>404</error-code>
          <location>/index.html</location>
    </error-page>
    

답변

면책 조항 :이 수정은 Alpha44에서 작동합니다

Angular.io API Preview에 나열된 HashLocationStrategy 를 구현하여 동일한 문제가 발생하여 해결했습니다 .

https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class.html

필요한 지시문을 가져 와서 시작하십시오.

import {provide} from 'angular2/angular2';
import {
  ROUTER_PROVIDERS,
  LocationStrategy,
  HashLocationStrategy
} from 'angular2/router';

마지막으로, 이렇게 부트 스트랩

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

경로는 http : // localhost / # / route 로 표시되며 새로 고침하면 올바른 위치에 다시로드됩니다.

희망이 도움이됩니다!


답변

기본적으로 Angular는 HTML5 pushstate를 사용합니다 ( PathLocationStrategyAngular 속어).
요청한 것과 같은 모든 요청을 처리하는 서버가 필요 index.html하거나 https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class (HashLocationStrategy 라우트 URL에 # 포함)로 전환해야 합니다. html

참조 https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/

로 전환하려면 HashLocationStrategy사용

> = RC.5 및 2.0.0 최종 업데이트

import {HashLocationStrategy, LocationStrategy} from '@angular/common';

@NgModule({
  declarations: [AppCmp],
  bootstrap: [AppCmp],
  imports: [BrowserModule, routes],
  providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
]);

또는 더 짧은 useHash

imports: [RouterModule.forRoot(ROUTER_CONFIG, {useHash: true}), ...

수입품이 모두 있는지 확인하십시오

새로운 (RC.3) 라우터

<base href="."> 

404도 발생할 수 있습니다.

대신에 필요합니다

<base href="/">

> = RC.x 업데이트

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
  // or since RC.2
  {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

import {provide} from '@angular/core';
import {
  PlatformLocation,
  Location,
  LocationStrategy,
  HashLocationStrategy,
  PathLocationStrategy,
  APP_BASE_HREF}
from '@angular/common';  

> = 베타 업데이트 16 가져 오기가 변경되었습니다

import {BrowserPlatformLocation} from '@angular/platform-browser';

import {provide} from 'angular2/core';
import {
  // PlatformLocation,
  // Location,
  LocationStrategy,
  HashLocationStrategy,
  // PathLocationStrategy,
  APP_BASE_HREF}
from 'angular2/router';
import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location';

<베타 .16

import {provide} from 'angular2/core';
import {
  HashLocationStrategy
  LocationStrategy,
  ROUTER_PROVIDERS,
} from 'angular2/router';

참조 https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26 파괴-변경


답변

나는 당신이보고있는 오류는 존재하지 않는 http : // localhost / route 를 요청하기 때문에 발생한다고 생각 합니다. 서버가 모든 요청을 기본 index.html 페이지에 매핑해야합니다.

Angular 2는 URL 끝에 해시를 사용하지 않고 기본적으로 html5 라우팅을 사용하므로 페이지를 새로 고치는 것은 다른 리소스에 대한 요청처럼 보입니다.


답변

기본 HTML 위치 전략을 사용하는 경우 모든 라우터 버전에서 일반적인 상황입니다.

브라우저 표시 줄의 URL이 일반적인 전체 HTML URL입니다 (예 🙂 http://localhost/route.

따라서 브라우저 표시 줄에서 Enter 키를 누르면라는 파일을 얻기 위해 서버로 전송되는 실제 HTTP 요청이 있습니다 route.

서버에는 그러한 파일이 없으며, 요청을 처리하고 응답을 제공하도록 express와 같은 것이 서버에 구성되어 있지 않으므로 서버는 route파일을 찾을 수 없기 때문에 404 Not Found를 리턴 합니다.

우리가 원하는 것은 서버가 index.html단일 페이지 응용 프로그램이 포함 된 파일 을 반환하는 것 입니다. 그런 다음 라우터는 /routeURL을 시작하고 처리하여 매핑 된 구성 요소를 표시해야합니다.

따라서 문제를 해결하려면 index.html404 Not Found와는 달리 요청을 처리 할 수없는 경우 서버가 단일 페이지 응용 프로그램 파일 이름이라고 가정 하여 반환하도록 서버를 구성해야합니다 .

이를 수행하는 방법은 사용중인 서버 측 기술에 따라 다릅니다. 예를 들어 Java가 서블릿을 작성 해야하는 경우 Rails에서 다릅니다.

구체적인 예를 들어, 예를 들어 NodeJ를 사용하는 경우 다음과 같은 미들웨어를 작성해야합니다.

function sendSpaFileIfUnmatched(req,res) {
    res.sendFile("index.html", { root: '.' });
}

그런 다음 미들웨어 체인의 맨 끝에 등록하십시오.

app.use(sendSpaFileIfUnmatched);

이것은 index.html404를 반환하는 대신 제공 되며 라우터가 작동하고 모든 것이 예상대로 작동합니다.


답변

이것이 index.html의 head 요소에 있는지 확인하십시오.

<base href="https://stackoverflow.com/">

Angular2 Routing & Navigation 문서 의 예제 는 대신 머리에 다음 코드를 사용합니다 (문서의 라이브 예제 노트에서 이유를 설명합니다).

<script>document.write('<base href="' + document.location + '" />');</script>

페이지를 새로 고치면 기본 href가 현재 document.location으로 동적으로 설정됩니다. 나는 이것이 문서를 감추고 플런저를 복제하려고 시도하는 사람들에게 혼란을 일으키는 것을 볼 수 있었다.


답변

index.html에 대한 모든 요청을 처리하도록 AppServer를 구성하지 않고 브라우저에서 URL을 입력하려면 HashLocationStrategy 를 사용해야합니다 .

구성하는 가장 쉬운 방법은 다음을 사용하는 것입니다.

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

대신에:

RouterModule.forRoot(routes)

HashLocationStrategy를 사용하면 URL은 다음과 같습니다.

http://server:port/#/path