How to serve an angular2 app in a node.js server

前端 未结 5 495
你的背包
你的背包 2021-01-01 23:41

I\'m building a web app using Angular2, to create the project I\'m using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 23:48

    None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
    So this is how I solved it. Angular routing works even on full page reload.

    function getRoot(request, response) {
       response.sendFile(path.resolve('./public/angular/index.html'));
    }
    
    function getUndefined(request, response) {
       response.sendFile(path.resolve('./public/angular/index.html'));
    }
    
    // Note the dot at the beginning of the path
    app.use(express.static('./public/angular'));
    
    app.get('/', getRoot);
    app.get('/*', getUndefined);
    

    NO angular base-href rewrite is required! Just use ng build or ng build --prod.

提交回复
热议问题