如何处理 Nodejs 中的 angular2 路由路径?

How to handle angular2 route path in Nodejs?

我正在使用 Angular2 开发 NodeJS 应用程序。在我的应用程序中,我有一个主页和搜索页面。对于主页,我有一个 HTML 页面,它将呈现 localhost:3000/ 并从主页用户导航到 searchlocalhost:3000/search 我通过 angular2 routes 处理的页面。

我没有搜索页面的页面,其视图由 angular2 呈现。但是当我直接点击 localhost:3000/search 时,因为我的节点应用程序中没有这个路由,它给出了错误。

我不知道如何在节点应用程序中处理这个问题?

您需要使用 HashLocationStrategy

import { LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(AppComponent, [
 ROUTER_PROVIDERS,
 provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

在您的 bootstrap 文件中。

如果您想使用 PathLocationStrategy(不带 #),您必须为您的服务器设置重写策略。

如果你直接在浏览器导航栏中输入localhost:3000/search,你的浏览器会向你的服务器发出'/search'的请求,这在控制台中可以看到(确保你勾选了'Preserve Log' 按钮)。

Navigated to http://localhost:3000/search

如果您 运行 一个完全静态的服务器,这会产生一个错误,因为服务器上不存在搜索页面。例如,使用 express,您可以捕获这些请求和 returns index.html 文件。 angular2 bootstrap kicks-in,你的@RouteConfig 中描述的 /search 路由被激活。

// example of express()
let app = express();
app.use(express.static(static_dir));

// Additional web services goes here
...

// 404 catch 
app.all('*', (req: any, res: any) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.status(200).sendFile(index_file);
});

我已经研究这个话题很长时间了,尝试了很多不起作用的方法。 如果您使用 angular-cli 和 express ,如果所选答案不适合您,我找到了解决方案。

试试这个节点模块:express-history-api-fallback

[ Angular ] 更改您的 app.module.ts 文件,在 @NgModule > 下导入如下:

RouterModule.forRoot(routes), ...

这就是所谓的:“位置策略”

您可能像这样使用“哈希位置策略”:

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

[快递和节点] 基本上你必须正确处理 URL,所以如果你想调用 "api/datas" 等,这不会与 HTML5 位置策略冲突。

在您的 server.js 文件中(如果您使用了 express 生成器,为了清楚起见,我将其重命名为 middleware.js)

第 1 步。- 需要 express-history-api-fallback 模块。

const fallback = require('express-history-api-fallback');

第 2 步。你可能有很多路由模块,某事。喜欢:

app.use('/api/users, userRoutes);
app.use('/api/books, bookRoutes); ......
app.use('/', index); // Where you render your Angular 4 (dist/index.html) 

注意你写的顺序,在我的例子中,我在 app.use('/',index);

下调用模块
app.use(fallback(__dirname + '/dist/index.html'));

* 确保它在你处理 404 之类的地方之前。像那样 。

这种方法对我有用:) 我正在使用 EAN 堆栈(Angular4 与 cli 、 Express 、 Node )