【问题标题】:Launch angular 4 from Hapi js从 Hapi js 启动 Angular 4
【发布时间】:2018-05-10 23:37:12
【问题描述】:

我有 hapi js 的后端和 angular 4 的前端。我有 2 台服务器来启动我的前端和后端。

我想从 hapi js 启动我的 Angular 应用程序,但我不知道该怎么做。我找到了https://github.com/guillaume-chs/angular4-hapijs,但它不起作用。你有更多的例子吗?

谢谢

【问题讨论】:

    标签: angular hapijs


    【解决方案1】:

    我猜 hapi.js 是父项目,而 Angular 4 只是“视图”,所以你需要做的是在 GET / 上提供 dist 文件夹下的静态 index.html 文件角度的构建。

    编辑:在 node.js 应用程序中以 Angular 作为视图项目,我使用这个 res.sendFile(${frontEndDist}/index.html)

    ngOnInit() 可能不需要if 语句

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

    在 node.js 应用中

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

    我想您可以轻松地将其转换为 hapi.js 语法 - 与 reply.file(//path to index.html) 相关的内容

    【讨论】:

    • 谢谢你的回答,我去试试。但是我每次都要构建我的项目,你觉得可以直接启动我的angular server吗
    • 没有问题:) 您不必每次都构建它。我正在运行我的本地 nodejs 应用程序和我的本地 angular 4 应用程序热重载。我会用 sn-p 更新我的答案。
    • 感谢您的帮助! :)
    • 所以,就我而言,我在 Heroku 中运行这个项目,它与运行 heroku local (node index.js) 的本地服务器和运行 ng serve --open 的本地 angular 一起使用
    猜你喜欢
    • 2023-03-04
    • 2018-02-12
    • 2015-11-04
    • 1970-01-01
    • 2018-02-05
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多