Launch angular 4 from Hapi js

2019-08-21 02:24发布

问题:

I have back-end with hapi js and front-end with angular 4. I have 2 servers to launch my front-end and my back-end.

I would like to launch my angular application from hapi js and I don't know how to do that. I found https://github.com/guillaume-chs/angular4-hapijs but it's not working. Do you have more examples?

Thank you

回答1:

I guess that hapi.js is the parent project and angular 4 is just the "view", so what you need to do is on GET / serve the static index.html file that is under dist folder after the build of angular.

Edit: In node.js app with angular as a view project I use this res.sendFile(${frontEndDist}/index.html)

ngOnInit() maybe the if statement is not needed

this.http.get(this.portURL)
      .toPromise()
      .then((res: any) => {
        const json = res.json();
        this.port = json.port;
        console.log(`port ${this.port}`);

        this.url = location.origin.replace(/^http/, 'ws');
        if (location.origin.includes('localhost')) {
          this.url = this.url.replace('4200', '5000');
        } else {
          this.url = this.url.replace('4200', this.port.toString());
        }

        this.initWebSocketConnection();
        console.log(`url ${this.url}`);
      })
      .catch((reason) => {
        console.log(reason);
      });

In node.js app

const server = express()
  .use(express.static(frontEndDist))
  .use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  })
  .get('/port', (req, res) => {
    res.json({port: port})
  })
  .get('*', (req, res) => {
    res.sendFile(`${frontEndDist}/index.html`);
  })
  .listen(port, () => {
    console.log(`Listening on ${port}`)
  });

I guess you can easily convert that to hapi.js syntax - something relevant to reply.file(//path to index.html)