我正在使用Angular2开发NodeJS应用程序。在我的应用程序中,我有一个主页和搜索页面。对于主页,我有一个HTML页面,它将为localhost:3000 /和主页用户导航到搜索,即我使用angular2路由处理的localhost:3000 /搜索页面。
我没有搜索页面的页面,其视图由angular2呈现。但是当我直接命中localhost:3000 / search因为我在我的节点应用程序中没有这个路由时它会给出错误。
我不知道如何在节点应用程序中处理这个?
如果您直接在浏览器导航栏中输入localhost:3000/search
,浏览器会向服务器发出“/搜索”请求,这可以在控制台中看到(请确保选中“保留日志”按钮)。
Navigated to http://localhost:3000/search
如果运行完全静态服务器,则会生成错误,因为服务器上不存在搜索页面。例如,使用express,您可以捕获这些请求并返回index.html文件。 angular2引导程序启动,并且@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);
});
您需要使用HashLocationStrategy
import { LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })
]);
在你的bootstrap文件中。
如果你想使用PathLocationStrategy(没有#),你必须为你的服务器设置重写策略。
我一直在挖这个话题很长一段时间,并尝试了许多不起作用的方法。如果您正在使用angular-cli和express,我找到了一个解决方案,如果所选答案不适合您。
试试这个节点模块:express-history-api-fallback
[Angular]在@NgModule> imports下更改app.module.ts文件,如下所示:
RouterModule.forRoot(routes), ...
这就是所谓的“位置策略”
您可能正在使用“Hash Location Strategy”,如下所示:
RouterModule.forRoot(routes, { useHash: true }) , ...
[Express&Node]基本上你必须正确处理URL,所以如果你想要调用“api / datas”等与HTML5位置策略不冲突的话。
在你的server.js文件中(如果你使用快速生成器,为了清楚起见,我将它重命名为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)