簡體   English   中英

2020年如何整合AngularSPA和Hapi?

[英]How to integrate AngularSPA and Hapi in 2020?

我研究了一堆文章並閱讀了大量文檔,但沒有太多結果。 I have a Angular SPA app that uses routing, when in localhost my application works but after deploying it to Heroku, these routings will try some GET request and HAPI will answer with error 404. The app endpoints of the REST services are ok and the Angular應用程序運行良好。 Angular路由鏈接我有

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="nav-item nav-link" routerLinkActive="active" href="/">Trades</a>
  <a class="nav-item nav-link" routerLinkActive="active" href="/stocks_list">Stocks</a>
</nav>

我嘗試了一些我在這里找到的技巧,但在編譯代碼時沒有成功,錯誤如下。

    this.server.ext('onPreResponse', (request, h) => {
            const response = request.response;
        
            if (request.response && 'isBoom' in request.response 
            && request.response.message !== 'Invalid request payload input') {
              return h.continue;
            }
        
            if (response.output.statusCode === 404) {
              return h.file('index.html');
            }
          });

此代碼不會在最新版本的 Hapi 中編譯

      [ERROR] 23:56:28 ⨯ Unable to compile TypeScript:
    src/app.ts:77:26 - error TS2339: Property 'output' does not exist on type 'Boom<any> | ResponseObject'.
      Property 'output' does not exist on type 'ResponseObject'.
    
    77             if (response.output.statusCode === 404) {
                                ~~~~~~
    src/app.ts:78:24 - error TS2339: Property 'file' does not exist on type 'ResponseToolkit'.
    
    78               return h.file('index.html');

這是我的 app.ts,唯一沒有編譯的部分是 onPreResponse

import { Boom } from '@hapi/boom';
import * as Hapi from '@hapi/hapi'
import { plugins } from './plugins'

const PORT = process.env.PORT || 3000
const Path = require('path');
const Inert = require('@hapi/inert');

export class App {
  
  server: Hapi.Server;

  constructor (private host: string){
      console.log(`Trying to connect at ${host} port ${PORT}`)
      this.server = new Hapi.Server({
          host: host,
          port: PORT,
          routes: {
            files: {
                relativeTo: Path.join(__dirname, 'frontend')
            },
            validate: {
                failAction: (request, h, err) => {
                    console.error(err);
                    throw err;
                }
            },
            cors: {
                origin: [
                    'http://0.0.0.0',
                    'http://127.0.0.1',
                    'http://localhost:4200',
                    'stocks-price.herokuapp.com'
                ], // an array of origins or 'ignore'          
                additionalHeaders: [
                    'Access-Control-Allow-Origin',
                    'Access-Control-Request-Method',
                    'Allow-Origin',
                    'Origin',
                    'access-control-allow-origin',
                    'access-control-request-method',
                    'allow-origin',
                    'origin',
                ]
            }
        }
    });
  }

  start = async () => {
      try {
          await this.server.register(Inert)
          await this.server.register(plugins)

          this.server.route({
            method: 'GET',
            path: '/{param*}',
            handler: {
              directory: {
                path: '.',
                redirectToSlash: true,
                lookupCompressed: true,
                index: true,
              },
            },
          });
        

          this.server.ext('onPreResponse', (request, h) => {
            const response = request.response;
        
            if (request.response && 'isBoom' in request.response 
            && request.response.message !== 'Invalid request payload input') {
              return h.continue;
            }
        
            if (response.output.statusCode === 404) {
              return h.file('index.html');
            }
          });

          await this.init();
          
          
          this.server.route({
            method: 'GET',
            path: '/{param*}',
            handler: {
                directory: {
                    path: [Path.join(__dirname, 'frontend')],
                    listing: false,
                    index: ['index.html']
                }
            }
          })
                  
          await this.server.start()

      } catch (err) {
          throw new Error(err);
          process.exit(1);
      }
  }

  init () {
      console.log('success on port: ' + this.server.info.port);
  }

}

任何幫助我都會很高興,JS 開發現在是一場噩夢,特別是當庫發生變化並且舊樣本不再工作時。

好吧,我不得不使用在路由上使用散列的解決方法,這就是訣竅。

集成所有 Angular2 和 Hapi 路由

參考這個問題,你會找到答案。 它比嘗試破解 Hapi 容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM