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

Khi*_*rad 34 c# asp.net-core angular visual-studio-2019 angular9

升级到 angular 9 后出现此错误。我使用的是 Visual Studio 2019,带有 angular 的 ASP .NET 核心。即使我创建新项目并将 angular 更新为 9 版本,它也会停止工作。

页面响应的完整列表是:

TimeoutException:Angular CLI 进程没有在 0 秒的超时时间内开始侦听请求。检查日志输出以获取错误信息。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"
  }
}
```
Run Code Online (Sandbox Code Playgroud)

小智 42

TL; 博士

遗憾的是,这个问题似乎与 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)。

完整答案

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

启动 Angular 服务器的核心引擎由两个类表示:AngularCliMiddleware ( https://git.io/JvlaL ) 和 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;
}
Run Code Online (Sandbox Code Playgroud)

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

有趣的是这应该有效

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

如果您 dotnet 运行该应用程序,节点服务器实际上会启动,只需在 Debug 模式下启用所有日志,找到“Starting @angular/cli on port ...”行并尝试在该端口上访问 localhost,您将看到您的角度应用程序正在运行。

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

就我所见,一旦您 dotnet 运行您的应用程序,就会按顺序生成一系列进程,但我没有注意到从 Angular 8 到 Angular 9 的命令行有任何区别。

我的理论是 Angular CLI 中的某些内容已更改,阻止该行在 stdout 中发送,因此 .net 代理不会捕获它,也无法检测 Angular 服务器何时启动。

根据这个问题:

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

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

  • 进度解决方案也是随机工作的。所以我想,它们都不起作用。 (2认同)
  • 这个解决方案对我不起作用,我正在使用的 Angular 版本 9 已经有进度= true,我正在本地主机上测试,不确定这是否是唯一的开发环境问题 (2认同)

opp*_*opp 30

我通过更改解决了它:

"scripts": {   
        "start": "ng serve",
Run Code Online (Sandbox Code Playgroud)

到:

 "scripts": {   
        "start": "echo Starting... && ng serve",
Run Code Online (Sandbox Code Playgroud)

package.json


fre*_*doo 9

这是我所做的

来自 Fairlie Agile,在 main.ts 中注释掉了这一行

export { renderModule, renderModuleFactory } from '@angular/platform-server';
Run Code Online (Sandbox Code Playgroud)

来自 Claudio Valerio 在 angular.json 中,设置

"progress": true,
Run Code Online (Sandbox Code Playgroud)

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


小智 6

正如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");
      }
    });
Run Code Online (Sandbox Code Playgroud)


小智 5

要解决严格模式错误,请从 main.ts 中删除此行

export { renderModule, renderModuleFactory } from '@angular/platform-server';
Run Code Online (Sandbox Code Playgroud)

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

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


小智 5

这是一个解决方法:

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

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

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

  • 这是在 Angular 11+.net 3.1 上对我有用的唯一修复 (2认同)

Kon*_*ten 5

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

"scripts": {
  "ng": "ng",
  "start": "ng serve --verbose",
  "build": "ng build", ...
}, ...
Run Code Online (Sandbox Code Playgroud)

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


小智 5

我在启动类的配置方法中更改了使用水疗管道配置,它对我有用。

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");
                }
            });
Run Code Online (Sandbox Code Playgroud)