16

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

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

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

4

3 回答 3

28

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

Navigated to http://localhost:3000/search

如果您运行完全静态的服务器,则会产生错误,因为服务器上不存在搜索页面。例如,使用 express,您可以捕获这些请求并返回 index.html 文件。angular2 bootstrap 启动,@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);
});
于 2016-01-18T21:42:02.953 回答
1

您需要使用 HashLocationStrategy

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

在您的引导文件中。

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

于 2016-01-18T07:42:45.000 回答
1

我一直在挖掘这个话题很长一段时间,并尝试了很多不起作用的方法。如果您使用 angular-cli 和 express ,如果所选答案不适合您,我找到了解决方案。

Try this node module : express-history-api-fallback

[ Angular ] Change your app.module.ts file , under @NgModule > imports as following :

RouterModule.forRoot(routes), ...

This is so called : " Location Strategy "

You probably were using " Hash Location Strategy " like this :

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

[ Express & Node ] Basically you have to handle the URL properly , so if you want call "api/datas" etc. that doesn't conflict with the HTML5 Location Strategy .

In your server.js file ( if you used express generator , I've rename it as middleware.js for clarity )

Step 1. - Require the express-history-api-fallback module.

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

Step 2 . You may have a lot of routes module , sth. like :

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

Becareful with the order you are writing , in my case I call the module right under app.use('/',index);

app.use(fallback(__dirname + '/dist/index.html'));

* Make sure it is before where you handle 404 or sth. like that .

This approach works for me : ) I am using EAN stack (Angular4 with cli , Express , Node )

于 2017-08-18T06:33:49.367 回答