programing

Angular 2: 브라우저를 통해 새로 고칠 때 404 오류가 발생합니다.

sourcejob 2023. 5. 24. 22:06
반응형

Angular 2: 브라우저를 통해 새로 고칠 때 404 오류가 발생합니다.

단일 페이지 응용프로그램을 "myapp"이라는 폴더 내의 서버에 저장했습니다.베이스의 URL을 http://example.com/myapp/ '로 변경하였습니다.

제 프로젝트는 두 페이지입니다.그래서 저는 Angular 2 라우팅을 구현합니다.기본 페이지를 로그인으로 설정했습니다.가 때할력을 치면.http://example.com/myapp/으로 " 브우저에자리로디됩니다션렉동으서내라다니▁automatic됩▁redirect▁in▁will션"로 리디렉션됩니다.http://example.com/myapp/login하지만 그 페이지를 새로 고치면,404 오류, 라말는것하고라고 말하는 http://example.com/myapp/login찾을 수 없습니다.

하지만 Lite 서버를 사용하여 프로젝트를 실행하면 모든 것이 작동합니다.이 index.은 "인덱스.html" 및 "URL"입니다."/"어떻게 고칠까요?

Angular 2 최종 버전에 대한 업데이트

app.module.ts에서:

  • 가져오기 추가:

      import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    
  • NgModule 공급자에서 다음을 추가합니다.

      {provide: LocationStrategy, useClass: HashLocationStrategy}
    

(app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}

대안

{useHash:true} 인수와 함께 RouterModule.forRoot를 사용합니다.

예:(각도 문서에서)

import { NgModule } from '@angular/core';
...

const routes: Routes = [//routes in here];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

정말로 원하는 사람들을 위해 (나처럼)PathLocationStrategyhtml, html5Mode) » 대신 (HashLocationStrategy방법: 타사 Wiki에서 html5Mode작동하도록 서버 구성:

사용하도록 한 경우 html5Mode를 사용할 수 .#문자가 URL에서 더 이상 사용되지 않습니다.#기호는 서버 측 구성이 필요하지 않으므로 유용합니다. 없이.#URL이 훨씬 좋아 보이지만 서버 쪽을 다시 써야 합니다.

여기서 저는 위키가 분실될 경우를 대비해 위키에서 세 가지 예만 복사합니다.다른 예는 키워드 "URL 다시 쓰기"(예: Firebase에 대한 이 답변)를 검색하여 찾을 수 있습니다.

아파치

<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;

    root /path/to/app;

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

다에대설에 대한 try_files

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>

사실, 브라우저 내의 실제 주소가 업데이트되고 있기 때문에 애플리케이션을 새로 고칠 때 404 오류가 발생하는 것이 일반적입니다(#/hashbang 접근법 없이).기본적으로 HTML5 기록은 Angular2에서 재사용하기 위해 사용됩니다.

오류를 하여 404 오류를 .index.html정의한 각 경로 경로에 대한 파일입니다.

HashBang 접근 방식으로 전환하려면 다음 구성을 사용해야 합니다.

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

import {MyApp} from './myapp';

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

이 경우 페이지를 새로 고치면 다시 표시됩니다(그러나 다음과 같은 메시지가 표시됩니다.#주소로).

이 링크를 통해 다음과 같은 이점을 얻을 수 있습니다.웹사이트를 새로 고치면 404점을 받습니다. 이것은 Angular2와 파이어베이스입니다.

도움이 되길 바래, 티에리

저도 같은 문제가 있었습니다.내 Angular 응용 프로그램이 Windows 서버에서 실행되고 있습니다.

루트 디렉터리에 web.config 파일을 만들어 이 문제를 해결했습니다.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" 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>
</configuration>

아마도 당신은 등록하는 동안 그것을 할 수 있을 것입니다.root와 함께RouterModule속성이 있는 두 번째 개체를 전달할 수 있습니다.useHash:true아래와 같이:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { ROUTES }   from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    RouterModule.forRoot(ROUTES ,{ useHash: true }),],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

Angular 2 rc4 이상을 사용하는 이 문서를 읽는 사용자의 경우, 위치 전략이 라우터에서 공통으로 이동된 것으로 나타납니다.당신은 그곳에서 그것을 수입해야 할 것입니다.

또한 '제공' 줄 주변의 괄호도 주의하십시오.

메인.ts

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

Visual Studio 2015에서 ASP.NET Core 1을 통해 Angular 2를 실행하는 경우 위르겐 구쉬의 이 솔루션이 유용할 수 있습니다.그는 블로그 게시물에서 그것을 설명합니다.그것은 저에게 최고의 해결책이었습니다.아래 제공된 C# 코드를 앱 바로 앞에 있는 Startup.cs public void Configure()에 배치합니다.정적 파일 사용();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

언급URL : https://stackoverflow.com/questions/35284988/angular-2-404-error-occur-when-i-refresh-through-the-browser

반응형