Angular万能投掷"Error at XMLHttpRequest.send"

Angular universal throwing "Error at XMLHttpRequest.send"

我最近将项目升级到 Angular 10 并添加了 angular 通用。构建应用程序没有问题,但是当我 运行 我的应用程序在开发环境中时,它抛出以下错误

ERROR Error at XMLHttpRequest.send (/Users/user/Documents/Web Projects/Freelance/my-project/dist/frontend/server/main.js:297667:19)

我正在使用以下命令 运行 应用程序

npm run dev:ssr

我也在 guards 中检查了 isPlatformBrowser,但还是不行。

任何帮助将不胜感激。

这可能对以后的任何人都有帮助。让拦截器处理 HTTP 调用解决了这个问题。在我的例子中,所有外部 API 调用都是绝对 URL。拦截器帮助我检查 URL 是相对的还是绝对的,并在必要时更新 URL。

import { Injectable, Inject, Optional } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import {Request} from 'express';
import {REQUEST} from '@nguniversal/express-engine/tokens';

@Injectable()
export class UniversalInterceptor implements HttpInterceptor {

  constructor(@Optional() @Inject(REQUEST) protected request: Request) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let serverReq: HttpRequest<any> = req;
    if (this.request && req.url.indexOf('http') !== 0) {
      let newUrl = `${this.request.protocol}://${this.request.get('host')}`;
      if (!req.url.startsWith('/')) {
        newUrl += '/';
      }
      newUrl += req.url;
      serverReq = req.clone({url: newUrl});
    }

    return next.handle(serverReq);
  }
}