Integrate all Angular2 and Hapi routes

不想你离开。 提交于 2021-02-08 07:39:44

问题


Situation

I'm developing a web application that uses Hapi server for REST calls and multi-page Angular2 website client-side.

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

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.

Issue

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!

Question

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).

Thank you in advance!

Edit: SOLUTION

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
    },

All Angular2 urls must be preceded by /#/ (e.g. localhost/#/home), which works great for me.


回答1:


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

    }

});

also added this to connection config

server.connection({
...
routes: {
    files: {
        relativeTo: Path.join(__dirname, './public')
    }
  }
});

Haven't found any smartest way to handle this



来源:https://stackoverflow.com/questions/40747229/integrate-all-angular2-and-hapi-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!