TimeoutException: Angular CLI 进程没有在 0 秒的超时期限内开始侦听请求

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds

升级到 angular 9 后出现此错误。我正在使用 visual studio 2019,ASP .NET 核心和 angular。即使我创建新项目并将 angular 更新到 9 版本,它也会停止工作。

页面响应的完整列表是:

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我的package.json是:

{
  "name": "webapplication10",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng run WebApplication10:server:dev",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "9.0.0",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "9.0.0",
    "@angular/compiler": "9.0.0",
    "@angular/core": "9.0.0",
    "@angular/forms": "9.0.0",
    "@angular/material": "~9.0.0",
    "@angular/platform-browser": "9.0.0",
    "@angular/platform-browser-dynamic": "9.0.0",
    "@angular/platform-server": "9.0.0",
    "@angular/router": "9.0.0",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "aspnet-prerendering": "^3.0.1",
    "bootstrap": "^4.4.1",
    "core-js": "^3.6.4",
    "jquery": "3.4.1",
    "oidc-client": "^1.10.1",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.900.1",
    "@angular/cli": "9.0.1",
    "@angular/compiler-cli": "9.0.0",
    "@angular/language-service": "9.0.0",
    "@types/jasmine": "^3.5.3",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "^12.12.27",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "typescript": "3.7.5"
  },
  "optionalDependencies": {
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "ts-node": "~8.4.1",
    "tslint": "~5.20.0"
  }
}
```

根据 https://developercommunity.visualstudio.com/solutions/446713/view.html 中的建议,您应该设置 StartupTimeout 配置设置。

基本上在Startup.cs:

 app.UseSpa(spa =>
    {
      spa.Options.SourcePath = "./";
      //Configure the timeout to 5 minutes to avoid "The Angular CLI process did not start listening for requests within the timeout period of 50 seconds." issue
      spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);
      if (env.IsDevelopment())
      {
        spa.UseAngularCliServer(npmScript: "start");
      }
    });

要解决严格模式错误,请从 main.ts

中删除此行
export { renderModule, renderModuleFactory } from '@angular/platform-server';

但这并不能解决超时问题。升级到 Angular 9 并使用 .NET 核心后,我也收到此错误。

运行 angular 应用程序使用 "ng serve",然后将您的启动 spa 脚本更改为使用 UseProxyToSpaDevelopmentServer 作为解决方法

TL;DR

遗憾的是,这个问题似乎与 Angular CLI 启动应用程序 angular 部分的方式发生了一些变化有关。根据这个问题:

https://github.com/dotnet/aspnetcore/issues/17277

建议的解决方案是在 angular.json 中设置 progress: true 或在 ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864) 之前执行简单的 echo。

完整答案

我挖掘了 asp.net 核心代码库 (https://github.com/dotnet/aspnetcore),查看 Angular 模板如何启动 Angular 应用程序。

启动angular服务器的核心引擎由两个类表示:AngularCliMiddleware(https://git.io/JvlaL) and NodeScriptRunner (https://git.io/Jvlaq).

在 AngularCliMiddleware 中我们找到这段代码(我删除了原来的注释并添加了一些我自己的注释来解释一些事情):

public static void Attach(ISpaBuilder spaBuilder, string npmScriptName)
{
    var sourcePath = spaBuilder.Options.SourcePath;
    if (string.IsNullOrEmpty(sourcePath))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
    }

    if (string.IsNullOrEmpty(npmScriptName))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName));
    }

    // Start Angular CLI and attach to middleware pipeline
    var appBuilder = spaBuilder.ApplicationBuilder;
    var logger = LoggerFinder.GetOrCreateLogger(appBuilder, LogCategoryName);
    var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger);

    var targetUriTask = angularCliServerInfoTask.ContinueWith(
        task => new UriBuilder("http", "localhost", task.Result.Port).Uri);

    SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, () =>
    {
        var timeout = spaBuilder.Options.StartupTimeout;
        return targetUriTask.WithTimeout(timeout,
            $"The Angular CLI process did not start listening for requests " +

            // === NOTE THIS LINE, THAT CARRIES THE "0 seconds" BUG!!!
            $"within the timeout period of {timeout.Seconds} seconds. " + 

            $"Check the log output for error information.");
    });
}

private static async Task<AngularCliServerInfo> StartAngularCliServerAsync(
    string sourcePath, string npmScriptName, ILogger logger)
{
    var portNumber = TcpPortFinder.FindAvailablePort();
    logger.LogInformation($"Starting @angular/cli on port {portNumber}...");

    var npmScriptRunner = new NpmScriptRunner(
        sourcePath, npmScriptName, $"--port {portNumber}", null);
    npmScriptRunner.AttachToLogger(logger);

    Match openBrowserLine;
    using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr))
    {
        try
        {
            // THIS LINE: awaits for the angular server to output
            // the 'open your browser...' string to stdout stream
            openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch(
                new Regex("open your browser on (http\S+)", RegexOptions.None, RegexMatchTimeout));
        }
        catch (EndOfStreamException ex)
        {
            throw new InvalidOperationException(
                $"The NPM script '{npmScriptName}' exited without indicating that the " +
                $"Angular CLI was listening for requests. The error output was: " +
                $"{stdErrReader.ReadAsString()}", ex);
        }
    }

    var uri = new Uri(openBrowserLine.Groups[1].Value);
    var serverInfo = new AngularCliServerInfo { Port = uri.Port };

    await WaitForAngularCliServerToAcceptRequests(uri);

    return serverInfo;
}

如您所见,StartAngularCliServerAsync 方法创建了一个新的 NpmScriptRunner 对象,它是一个包装器基本上,Process.Start 方法调用附加记录器,然后等待进程的 StdOut 发出与“在 httpSOMETHING... 上打开浏览器”相匹配的内容。

有趣的是这应该有用

如果您在 ClientApp 文件夹中 运行 ng serve(或 npm 运行 start),一旦服务器启动,它仍会发出输出“在 http...上打开浏览器”。

如果你 dotnet 运行 应用程序,节点服务器实际启动,只需在调试模式下启用所有日志,找到“Starting @angular/cli on port ...”行并尝试访问该端口上的本地主机,您会看到您的 angular 应用程序是 运行ning.

问题是由于某种原因,StdOut 不再获得“打开浏览器”行,它也不是由记录器编写的......似乎在某种程度上来自 ng serve 的特定输出行是被阻止,就像它不再在标准输出流中发送一样。 WaitForMatch 方法在 5 秒后超时,并从 WithTimeout 扩展方法的代码中捕获,该方法输出(错误的)“... 0 秒 ...”消息。

就我所见,一旦你 dotnet 运行 你的应用程序,一系列进程按顺序产生,但我没有注意到命令行与 Angular 8 有任何区别至 Angular 9.

我的理论是 Angular CLI 中的某些内容已更改,阻止该行在标准输出中发送,因此 .net 代理不会捕获它并且无法检测到 angular 服务器已启动。

根据本期:

https://github.com/dotnet/aspnetcore/issues/17277

建议的解决方案是在 angular.json 中设置 progress: true 或在 ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864) 之前执行简单的 echo。

这是我做的

来自 Fairlie Agile,在 main.ts

中注释掉这一行
export { renderModule, renderModuleFactory } from '@angular/platform-server';

来自克劳迪奥·瓦莱里奥 在 angular.json 中,设置

"progress": true,

现在我可以通过单击 F5/运行 IIS Express运行 应用程序

解决方法如下:

  • 在 package.json 中将启动脚本从 "ng serve" 更改为 "ngserve"
"scripts": {
  "start": "ngserve",
  • 在同一目录中创建一个文件 ngserve.cmd,内容如下:
@echo ** Angular Live Development Server is listening on localhost:%~2, open your browser on http://localhost:%~2/ **
ng serve %1 %~2

现在 Dotnet 得到了它正在等待的行。之后命令 ng serve 将启动服务器(所以实际上 Angular Live Development Server 还没有监听),浏览器将打开,首先它不会工作(ng serve 仍在编译),但是如果过一会再按reload应该就可以了

这只是一种解决方法,但对我们有用。

在 package.json 中将 ng serve 更改为 ng serve --host 0.0.0.0

我通过更改解决了它:

"scripts": {   
        "start": "ng serve",

至:

 "scripts": {   
        "start": "echo Starting... && ng serve",

package.json

我像这样在文件 package.json 中添加了详细的服务过程。

"scripts": {
  "ng": "ng",
  "start": "ng serve --verbose",
  "build": "ng build", ...
}, ...

不知道它为什么起作用,但我感觉它在某种程度上与导致与 echo 相同的减速有关。

在我的案例中,存在 SpaServices 或 ts-node 未捕获的 TypeScript 编译错误。有些引用使用相同的文件名和不同的命名空间,这让运行时编译器感到困惑。在ClientApp文件夹中执行ng build,确保没有错误。

如果您只做后端工作,请在您的startup.cs中注释掉

spa.UseAngularCliServer(npmScript: "start");

并添加

spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");

像这样...

//spa.UseAngularCliServer(npmScript: "start");
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");//Todo Switch back for SPA Dev

运行 通过 npm 启动来自 cmd(在 ClientApp 目录中)的 SPA。

然后当您的 运行 或从 Visual Studio 调试您的完整应用程序时,它会旋转得更快。

None 这里的解决方案对我有用。 在我将解决方案的组件升级到最新版本后,问题就开始了。 唯一对我有用的是将我的全局 angular cli 升级为与本地版本相同的版本:

npm uninstall -g angular-cli
npm cache clean
npm cache verify
npm install -g @angular/cli@latest

最好的方法是在启动时插入这一行

spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");

然后 运行 或从 Visual Studio 调试您的应用。

出于开发目的,如果您收到 'TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds.' 的错误。

请按照以下 2 个对我也适用的步骤进行操作:

在命令提示符下,运行 'ng serve' 命令到 运行 angular 解决方案。 在 startup.cs 文件中,将启动超时更改为分钟。即使它不会花费那么多时间,因为 angular 解决方案已经 运行ning。 -> spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);

如果对您有帮助,请标记答案!!

谢谢。

I have changed in use spa pipeline configuration in configure method of startup class, It works for me.

app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501
                spa.Options.StartupTimeout = new System.TimeSpan(0, 15, 0);
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

运行 npm install -g @angular/cli 来自命令提示符

"scripts": {
    "ng": "ng",
    "start": **"ng serve --port 33719 --open",**
    "build": "ng build",

使用 package.json

中以粗体显示的设置

更改为 .NET5 解决了我的问题。 你也可以试试这个:

 "scripts": {   
    "start": "echo start && ng serve",

"start": "ng serve --port 0000",

在package.json

我 运行 遇到了类似的问题,我在 package.json 文件

中进行了以下更新
"scripts": {
    "ng": "ng",
    "start": "echo hello && ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
}

请参阅 [dotnet/angular - issues/17277]

中的 github 分辨率

我做了所有这些成功的建议。但是超时问题仍然存在。 就我而言,以下对我有用,(将附上所有步骤)

  1. main.ts 中注释以下行以修复 strict mode 问题

    export { renderModule, renderModuleFactory } from '@angular/platform-server';

  2. package.json 文件中将 ng serve 更改为 echo Starting && ng serve

  3. 只需使用 Node.js 命令提示符手动 运行 ng serve 命令。然后尝试运行 Visual Studio中的项目。

我的 Visual Studio 在调试时崩溃后收到此错误。我无法使用上述任何解决方案让它消失。最后我删除了我的项目并从源代码中克隆了代码。之后它加载得很好。