部署到Http Server时,Angular 2路由不起作用

问题描述 投票:27回答:16

我将开发一个简单的Angular 2应用程序。我使用Angular CLI创建了一个带路由的项目,并使用'ng generate component'命令向应用添加了几个组件。然后我在app-routing.module.ts中指定了路由,如下所示。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { UserComponent } from './user/user.component';
import { ErrorComponent } from './error/error.component';
import { SpecialpageComponent } from './specialpage/specialpage.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'about',
    component: AboutComponent
  },
    {
    path: 'user',
    component: UserComponent
  },
  {
    path: 'specialpage',
    component: SpecialpageComponent
  },
  {
    path: '**',
    component: ErrorComponent
  }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

app.module.ts如下。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ErrorComponent } from './error/error.component';
import { UserComponent } from './user/user.component';
import { SpecialpageComponent } from './specialpage/specialpage.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent,
    ErrorComponent,
    UserComponent,
    SpecialpageComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我没有为其他组件添加任何修改。然后我使用'ng serve'命令部署应用程序,该应用程序与链接正常工作。例如:http://localhost:4200/about

enter image description here

但是当我在http-server中部署项目时,链接无法按预期工作。我使用'http-server ./dist'命令部署应用程序,应用程序部署正常,但链接不起作用。当我去'http://localhost:4200/about'时,它会给出404错误。

enter image description here

我做错了吗?为什么'ng-serve'工作和'http-server'不起作用?

任何帮助,将不胜感激。提前致谢。

我已将我的项目上传到github

angular npm angular2-routing angular-cli angular2-template
16个回答
24
投票

这个问题通过实施HashLocationStrategy来解决,#HashLocationStrategy to AppModule providers添加到您的所有路线。你可以通过添加 providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}], 来实现这一目标。

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

并添加相应的导入

HashLocationStrategy

这将解决您的问题。

如果你不想使用PahtLocationStrategy,你可以使用https://angular.io/api/common/PathLocationStrategy,因此你的Angular应用程序不会在URL中显示Hash。有关它的更多详细信息,请查看官方链接:here


0
投票

您应该尝试从应用程序应初始化的位置指定构建中的URL:

http://domain-name/main

0
投票

这个特定问题面临的确切原因是您的服务器设置。

因此,当您实施应用程序时,您必须采取某些步骤。其中一个基本步骤是标记路径的特定段:https://blog.angularindepth.com/deploy-an-angular-application-to-iis-60a0897742e7,其中main是路径段必须用作服务器设置中的标识符,当涉及到节点后端时,请说出server.js或app.js或用于IIS和Tomcat部署的webconfig文件。

标记特定段的原因是,当服务器收到带有该特定段的任何请求时,您需要将其重新路由到www或公共文件夹中的应用程序,以便角度路由器启动。

此过程称为url重写。因此,如果Web服务器或应用服务器取决于应用程序大小不在您的控制之下,那么请使用hashLocationStratergy,否则使用pathLocationStartergy总是很好,因为它在历史跟踪和其他美学和性能优势方面很有用。

要了解更多信息,您可以访问以下链接:

对他们来说:<base href="./home">


0
投票

在基本href字符串中添加一个点。

正确

<base href="/home">

错误

http://www.wisdomofjim.com/blog/solved-problems-with-resource-loading-failures-when-deploying-angular-2-webapps-live

export const routes: Routes =[ **{ path: '', redirectTo: '/', pathMatch: 'full'},** { path: 'about', component: AboutComponent}, { path: 'user', component: UserComponent}, { path: 'specialpage', component: SpecialpageComponent}, { path: '**', component: ErrorComponent} ];


-1
投票
providers:[]

看看blockquote的内容。然后你在app.module.ts的import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent} from './app.component'; import {appRoutes} from './app.routes'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], RouterModule.forRoot(appRoutes , {useHash: true})], providers: [], bootstrap: [AppComponent], }) export class AppModule {} 上给出了“HttpModule”的名字

谢谢。


-1
投票

您可以在注册RouterModule.forRoot时执行此操作,您可以传递具有属性{useHash:true}的第二个对象,如下所示:

<base href="/">
 to 
<base href="./">

-1
投票

更改index.html

http://localhost:4200/

因为我们使用的是Tomcat,所以我们已经提到过这个(。)的路由是基于这个(/)所以像http-server一样

我的意思是正常运行服务你只看到http://localhost:8080/dist/

但是在服务器中运行你已经将你的构建放入web应用程序(dist)中

所以它来了

<base href="./">

所以你需要添加RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [L]

我认为这是你可能解决的问题。


-1
投票

在项目文件夹中创建.htaccess文件然后写入

https://angular.io/guide/deployment

点击此链接:qazxswpoi


12
投票

这是因为http-server不支持像lite-server或web pack-dev服务器这样的回退。这就是为什么它显示404未找到。解决此问题有2个解决方案2解决方案:

  1. 您可以像上面提到的那样使用HashLocationStrategy。
  2. 如果您将其部署到Apache或IIS服务器,那么您可以简单地添加http://localhost:your-port提到的配置!

注意:对于开发,您可以使用lite-server。

希望这会帮助你。


6
投票

它会发生,因为它会找到一个关于哪个页面根本不在里面的页面因此404.可能的选项:

  1. 如果你想使用http-server,那么使用代理将所有内容重定向到-P。 选项:--proxy-P http://someurl.com将所有无法在本地解析的请求代理到给定的URL。例如:var express = require('express'); var app = express(); var path = __dirname + '/public'; var port = 8080; app.use(express.static(path)); app.get('*', function(req, res) { res.sendFile(path + '/index.html'); }); app.listen(port);
  2. 根本不要使用快递。使用快速创建自己的http服务器并将所有内容重定向到index.html 假设公共是你的文件夹,你保留所有转换的东西。 providers: [{provide: LocationStrategy, useClass: PathLocationStrategy}]

5
投票

我已经在AppModule Providers中添加了这个问题来解决这个问题:

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

和进口

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

然后我创建了.htaccess:

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

没有#在URL中的一切都很棒:)


3
投票

它将以这种方式解决:

案例1:对于小于Angular 5.1的版本

1)使用如下所述的HashLocationStrategy:在AppModule中执行以下操作。

1.1)providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]

1.2)RouterModule.forRoot

情况2:对于等于或大于Angular 5.1的版本

2.1)Angular在SameUrlNavigation上引入了这个属性,用于克服服务器上的刷新问题。

2.2)将onSameUrlNavigation添加到imports数组中的@ngModule({ imports: [ RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’}) ], exports: [RouterModule], });

a)在应用程序主路由模块中,i,e app.routing.module.ts / app.routing.ts添加属性

见下文:

RewriteEngine On
  # If an existing asset or directory is requested go to it as it is
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]
  # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

希望它对某人有所帮助。


1
投票

对于Apache服务器:

在生产服务器中

在项目根目录中添加或创建“.htaccess”文件,向.htaccess文件添加重写规则,如图所示

https://www.npmjs.com/package/angular-http-server

1
投票

如果你像我一样想要不做任何代码更改,只需使用它:

.htaccess


0
投票

对于Apache Server

  • 创建文件名index.html
  • 编辑该文件并写入index.php而不是.htaccess
  • 对于那些没有任何代码的人,可以在 RewriteEngine On # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html 文件中编写以下代码:https://httpd.apache.org/docs/current/howto/htaccess.html
  • 此代码可能不适用于SSL证书 - 请联系您的托管服务提供商或访问https://angular.io/guide/deployment以参考文档。

0
投票

根据RewriteEngine On # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html 的文档(Apache,您也可以查找nginx)您需要使用.htaccess文件将服务器指向index.html

Ng build --prod --base-href="http://your.url.com/subdirectory/etc"

RewriteRule ^ /index.html

© www.soinside.com 2019 - 2024. All rights reserved.