整合所有Angular2和Hapi路线 [英] Integrate all Angular2 and Hapi routes
问题描述
情况
我正在开发一个使用Hapi服务器进行REST调用和多页Angular2网站客户端的Web应用程序.
I'm developing a web application that uses Hapi server for REST calls and multi-page Angular2 website client-side.
Hapi通过以下方式将所有Angular2文件提供给客户端:
Hapi serves all Angular2 files to the client with:
let serverDirPath = path.resolve(__dirname);
server.route({
method: "GET",
path: "/{param*}",
config: {
auth: false,
handler: {
directory: {
path: path.join(serverDirPath, "../client"),
index: true
}
}
}
});
成功调用服务器根目录将返回"index.html",之后Angular2网站可以正常运行!所有对Hapi定义的路由的调用也可以正常工作.
Calling the server root successfully returns "index.html", and after that the Angular2 website works perfectly! All calls to Hapi-defined routes also works fine.
问题
但是,如果我对任何Angular2定义的路由执行GET(例如到达页面"/users"),则Hapi无法找到该路由并返回错误404.这可能是因为未在Hapi服务器.请注意,如果我从"index.html"页面导航到那里,那么"/users"路由就可以完美地工作!
However, if I execute a GET to any Angular2-defined route (for example to reach page "/users"), Hapi can't find the route and returns error 404. This is probably because the route is not defined on Hapi server. Please note that the "/users" route works perfectly if I navigate to there from the "index.html" page!
问题
如何通过直接GET呼叫访问"/用户"页面?如果可能的话,我想将对Hapi路由的所有调用重定向到相应的Angular2路由(如果存在).
How can I reach "/user" page with a direct GET call? If possible, I want to redirect all calls to Hapi routes to corresponding Angular2 routes (if they exist).
提前谢谢!
解决方案
我解决了!在app.module.ts的提供者声明中,我添加了以下内容:
I solved it! In the app.module.ts, in the providers declaration, I added this:
{
// Strategy to serve pages with /#/{path}. It's required to resolve Angular2 routes when using hapi.
provide: LocationStrategy,
useClass: HashLocationStrategy
},
所有Angular2网址都必须以/#/开头(例如localhost/#/home),这对我来说非常有用.
All Angular2 urls must be preceded by /#/ (e.g. localhost/#/home), which works great for me.
推荐答案
我遇到了同样的问题,并且制作了自定义路由处理程序,就像这样
I had the same problem and I have made the custom route handler, something like this
server.route({
method: 'GET',
path: '/{files*}',
handler: function(req, reply, next) {
var reg = /(\.js)|(\.css)|(\.png)|(\.jpg)|(\.jpeg)|(\.eot)|(\.woff)|(\.ttf)|(\.eot)|(\.svg)/;
if(req.params.files && reg.test(req.params.files)) {
reply.file(req.params.files);
}
else{
reply.file('index.html');
}
}
});
还将其添加到连接配置
server.connection({
...
routes: {
files: {
relativeTo: Path.join(__dirname, './public')
}
}
});
还没有找到最聪明的方法来解决这个问题
Haven't found any smartest way to handle this
这篇关于整合所有Angular2和Hapi路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!