繁体   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