使用Angular和Express自定义404页面

时间:2018-05-24 10:18:48

标签: node.js angular express

我正在使用MEAN堆栈,我正在尝试使用Angular为我的项目构建自定义404页面。

在Angular app.module.ts 中,我写了这个:

const appRoutes: Routes = [
    {
        path: 'students',
        component: StudentComponent,
        data: {title: 'Student List'}
    },
    {
        path: 'student-details/:id',
        component: StudentDetailComponent,
        data: {title: 'Student Details'}
    },
    {
        path: 'student-create',
        component: StudentCreateComponent,
        data: {title: 'Create a new Student'}
    },
    {
        path: 'student-edit/:id',
        component: StudentEditComponent,
        data: {title: 'Edit Student'}
    },
    {
        path: '',
        redirectTo: '/students',
        pathMatch: 'full'
    },
    {
        path: '**',
        component: PageNotFoundComponent,
        data: {title: 'Page Not Found'}
    }
];

@NgModule({
    declarations: [
        AppComponent,
        StudentComponent,
        StudentDetailComponent,
        StudentCreateComponent,
        StudentEditComponent,
        PageNotFoundComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        RouterModule.forRoot(
            appRoutes,
            {enableTracing: true}
        )
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

但实际上我认为当我写一个不存在的URL时,Express会做出响应,而不是Angular。我知道Express正在回答,因为当我从 server.js 中删除此代码时:

app.use(function(req, res, next) {
   var err = new Error('Not Found');
   err.status = 404;
   next(err);
});

当我写一个不存在的网址时,我会得到答案" 无法获取/ urlThatDoesntExist "。
问题是在Angular中设置的其他路由URL是有效的,但404页面不是。

我使用Express来使用以下方式为Angular应用程序提供服务:

app.use('/', express.static(path.join(__dirname, 'dist')));

如何将Angular 404页面设置为Express以上?谢谢!

1 个答案:

答案 0 :(得分:1)

如果您希望每个请求都达到角度(因此您可以在客户端处理404),您可以使用这样的快速路线:

//  all routes lead to to index.html
const router = express.Router();
router.get('*', (req, res) => {
  res.sendFile(path.join(DIR, 'index.html'));
});
this.express.use('*', router);