如何在Nodejs中处理angular2pathpath

我正在使用Angular2开发NodeJS应用程序。 在我的应用程序中,我有一个主页和search页面。 对于主页我有一个HTML页面,将呈现为本地主机:3000 /和从主页用户导航到search ie localhost:3000 /search页面,我通过angular2路线处理。

我没有search页面的视图由angular2呈现。 但是当我直接打本地主机:3000 /search,因为我没有这个路由在我的节点的应用程序,它会给出错误。

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

如果您直接在浏览器导航栏中inputlocalhost:3000/search ,浏览器会向您的服务器发出“/ search”请求(可以在控制台中查看)(请确保选中“保留日志”button)。

 Navigated to http://localhost:3000/search 

如果运行完全静态的服务器,则会生成一个错误,因为服务器上不存在search页面。 例如,使用快递,您可以捕获这些请求并返回index.html文件。 在您的@RouteConfig中描述的angular2引导启动和/searchpath被激活。

 // 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); }); 

你需要使用HashLocationStrategy

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

在你的引导文件中。

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

我一直在深入挖掘这个话题,并尝试了很多不工作的方法。 如果你正在使用angular-cli和express,如果select的答案不适合你,我find了一个解决scheme。

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

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

 RouterModule.forRoot(routes), ... 

这就是所谓的“定位策略”

您可能正在使用如下的“哈希位置策略”:

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

[Express&Node]基本上,你必须正确处理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 with cli,Express,Node)