Angular 2路由在部署到Http服务器时不起作用

Angular 2路由在部署到Http服务器时不起作用,angular,npm,angular2-routing,angular-cli,angular2-template,Angular,Npm,Angular2 Routing,Angular Cli,Angular2 Template,我将开发一个简单的Angular 2应用程序。我使用Angular CLI创建了一个带有路由的项目,并使用“ng generate component”命令向应用程序添加了几个组件。然后我在app routing.module.ts中指定了如下路由 import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } fr

我将开发一个简单的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 { } 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 { } 从“@angular/core”导入{NgModule}; 从'@angular/router'导入{Routes,RouterModule}; 从“./home/home.component”导入{HomeComponent}; 从“./about/about.component”导入{AboutComponent}; 从“./user/user.component”导入{UserComponent}; 从“./error/error.component”导入{ErrorComponent}; 从“./specialpage/specialpage.component”导入{SpecialpageComponent}; 常数路由:路由=[ { 路径:“”, 组件:HomeComponent }, { 路径:“关于”, 组件:大约组件 }, { 路径:“用户”, 组件:用户组件 }, { 路径:“specialpage”, 组件:SpecialpageComponent }, { 路径:'**', 组件:ErrorComponent } ]; @NGD模块({ 导入:[RouterModule.forRoot(路由)], 导出:[路由模块], 提供者:[] }) 导出类AppRoutingModule{} 应用程序模块.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 { } 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 { } 从“@angular/platform browser”导入{BrowserModule}; 从“@angular/core”导入{NgModule}; 从'@angular/forms'导入{FormsModule}; 从'@angular/http'导入{HttpModule}; 从“./app routing.module”导入{AppRoutingModule}; 从“./app.component”导入{AppComponent}; 从“./home/home.component”导入{HomeComponent}; 从“./about/about.component”导入{AboutComponent}; 从“./error/error.component”导入{ErrorComponent}; 从“./user/user.component”导入{UserComponent}; 从“./specialpage/specialpage.component”导入{SpecialpageComponent}; @NGD模块({ 声明:[ 应用组件, HomeComponent, 关于组件, 错误组件, 用户组件, 特殊部件 ], 进口:[ 浏览器模块, FormsModule, HttpModule, 批准模块 ], 提供者:[], 引导:[AppComponent] }) 导出类AppModule{} 我没有为其他组件添加任何修改。 然后,我使用“ng serve”命令部署了应用程序,该应用程序可以很好地处理链接。 例如:

但当我在http服务器中部署项目时,链接并没有按预期工作。我使用“http server./dist”命令部署了应用程序,应用程序部署得很好,但链接不起作用。当我转到“”时,它给出404错误

我做错什么了吗?为什么“ng server”起作用而“http服务器”不起作用

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


我已将我的项目上载到。

这将发生,因为它会找到一个关于的页面,该页面根本不在404中。可能的选择:

  • 如果您想使用http服务器,那么使用一个代理,它会将所有内容重定向到

    选项:
    -P
    -proxy
    将无法在本地解析的所有请求代理到给定的url。e、 g.:
    -Phttp://someurl.com

  • 根本不要使用express。使用express创建自己的http服务器&将所有内容重定向到index.html

    <base href="/">
     to 
    <base href="./">
    
    假设public是您保存所有传输内容的文件夹

    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);
    
  • 请看blockquote的内容。 然后在app.module.ts中的
    提供者:[
    处给出“HttpModule”的名称


    谢谢。

    通过实施
    HashLocationStrategy
    解决此问题,该策略将
    #
    添加到您的所有路线中。您可以通过向AppModule提供程序添加
    HashLocationStrategy来实现这一点

        providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    
    并添加相应的导入

       import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    
    这会解决你的问题

    如果你不想使用HashLocationStrategy,你可以使用PahtLocationStrategy,这样你的Angular应用程序就不会在URL中显示Hash。
    有关它的更多详细信息,请查看官方链接:

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

    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 {}
    

    这是因为http服务器不支持类似lite server或web pack dev server的回退。这就是它显示未找到404的原因。 解决此问题有两种解决方案:

  • 您可以像上面提到的那样使用HashLocationStrategy
  • 如果要将其部署到Apache或IIS服务器,则只需添加前面提到的配置即可 注意:对于开发,您可以使用lite服务器。

    希望这将对您有所帮助。

    更改index.html

    <base href="/">
     to 
    <base href="./">
    
    因此,您需要添加


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

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

    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]
    
    请点击此链接:
    对于Apache服务器:

    在生产服务器中

    将“.htaccess”文件添加或创建到项目根目录中,将重写规则添加到.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
    

    这将通过以下方式解决:

    案例1:适用于角度小于5.1的版本

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

    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 { } 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 { } 1.1)
    从“@angular/common”导入{HashLocationStrategy,LocationStrategy}

    1.2)
    提供程序:[{provide:LocationStrategy,useClass:HashLocationStrategy}]

    案例2:对于等于或大于5.1的版本

    2.1)Angular在ameurlNavigation上引入了此属性,以解决服务器上的刷新问题

    2.2)在导入数组中的
    RouterModule.forRoot
    中添加onSameUrlNavigation

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

    见下文:

    @ngModule({
    
        imports: 
        [
           RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})
        ],
    
        exports: [RouterModule],
     });
    

    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

    Ng build --prod --base-href="http://your.url.com/subdirectory/etc"
    
    <base href="./home">
    
    <base href="/home">
    
    npm i -D  lite-server
    
    "scripts": {
       "ci:serve:employee-onboarding": "ng build --prod --project=employee-onboarding && lite-server -c lite-server-config.json"
    }
    
    {
      "port": 4201,
      "server": { "baseDir": "dist/apps/employee-onboarding" }
    }
    
    @Configuration
    class WebMVCCustomConfiguration implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:static").resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) {
                        String path = "static/";
                        path += (resourcePath.contains(".") && !resourcePath.equals("index.html")) ? resourcePath : "index.html";
    
                        Resource resource = new ClassPathResource(path);
                        return resource.exists() ? resource : null;
                    }
                });
        }
      }