3

開発用に ng serve を介して Angular アプリを実行していますが、エラーは発生していません。ただし、SSR を使用すると、ngOnInit メソッドの一部として http 要求を行うコンポーネントをロードするたびに、サーバー ログにエラーが記録されます。私の戦略に何か問題がありますか?

エラーをグーグルで検索しても、有用な情報は見つかりませんでした。ページが完全に読み込まれる前にリクエストを送信するか、他の方法を使用する必要がありますか? もしそうなら、どうすればいいですか?

http-proxy-middleware パッケージを使用して、django サーバーにリクエストを送信しています。https://github.com/chimurai/http-proxy-middleware

これは、リクエストが ngOnInit の一部として行われたときに発生するエラーです。

ERROR Error
    at XMLHttpRequest.send (C:\{...}\dist\{...}\server\main.js:201490:19)
    at Observable.rxjs__WEBPACK_IMPORTED_MODULE_1__.Observable [as _subscribe] (C:\{...}\dist\{...}\server\main.js:23724:17)
    at Observable._trySubscribe (C:\{...}\dist\{...}\server\main.js:186583:25)
    at Observable.subscribe (C:\{...}\dist\{...}\server\main.js:186569:22)
    at scheduleTask (C:\{...}\dist\{...}\server\main.js:106745:32)
    at Observable.rxjs__WEBPACK_IMPORTED_MODULE_7__.Observable [as _subscribe] (C:\{...}\dist\{...}\server\main.js:106807:13)
    at Observable._trySubscribe (C:\{...}\dist\{...}\server\main.js:186583:25)
    at Observable.subscribe (C:\{...}\dist\{...}\server\main.js:186569:22)
    at subscribeToResult (C:\{...}\dist\{...}\server\main.js:196664:23)
    at MergeMapSubscriber._innerSub (C:\{...}\dist\{...}\server\main.js:191854:116)

私のテストコンポーネントの関連部分は次のとおりです。

export class TestComponent implements OnInit {
  output: String = "The server is not running or is not connected"

  constructor(private httpTestService: HttpTestService) { }

  ngOnInit(): void {
    this.testGetRequest();
  }

  testGetRequest() {
    this.httpTestService.testGetRequest().subscribe(temp => {
      this.output = temp.message; // response is json with a 'message' attribute
    });
  }

}

ここに私の HttpTestService の関連部分があります:

import { HttpClient } from '@angular/common/http';
  constructor(private http: HttpClient) { }

  testGetRequest(): Observable<any> {
    return this.http.get('/api/endpoint1');
  }

server.ts のこの部分が重要である可能性があると思います。

import { createProxyMiddleware } from 'http-proxy-middleware';
export function app() {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/.../browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // re-route requests to /api/ to the django REST api
  server.use('/api/**', createProxyMiddleware({ target: 'http://localhost:8000', changeOrigin: true }));

SSR で実行している場合でも、サーバー コンソールに表示されるエラーを除いて、アプリは正常に機能します。

4

1 に答える 1