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

2020-02-12 c# angular asp.net-core visual-studio-2019 angular9

I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.

Complete list of page response is :

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)

My package.json is:

{
  "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"
  }
}
```

Answers

As suggested in https://developercommunity.visualstudio.com/solutions/446713/view.html, you should setup the StartupTimeout configuration setting.

Basically in 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");
      }
    });

to resolve the strict mode error remove this line from main.ts

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

This doesn't resolve the timeout issue however. I am also getting this error after upgrading to Angular 9 and using .NET core.

Running the angular app using "ng serve" and then changing your startup spa script to use UseProxyToSpaDevelopmentServer works as a work-around

TL;DR

Sadly the issue seems related to some changes in the way Angular CLI starts up the angular part of the application. As per this issue:

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

proposed solutions are to set progress: true in angular.json or perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).

Full answer

I dug the asp.net core code base (https://github.com/dotnet/aspnetcore), looking how the Angular template starts up the Angular application.

The core engine that starts up the angular server is represented by two classes: AngularCliMiddleware (https://git.io/JvlaL) and NodeScriptRunner (https://git.io/Jvlaq).

In AngularCliMiddleware we find this code (I removed the original comments and added some of my own to explain a couple of things):

    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;
    }

As you can see, the StartAngularCliServerAsync method creates a new NpmScriptRunner object, that is a wrapper around a Process.Start method call, basically, attaches the logger and then waits for the StdOut of the process to emit something that matches "open your browser on httpSOMETHING...".

Fun thing is this should work!

If you run ng serve (or npm run start) in ClientApp folder, once the server starts it still emit the output "open your browser on http...".

If you dotnet run the application, the node server actually starts, just enable all the logs in Debug mode, find the "Starting @angular/cli on port ..." line and try visiting localhost on that port, you'll see that your angular application IS running.

Problem is that for some reason the StdOut is not getting the "open your browser on" line anymore, nor it is written by the logger... it seems that in some way that particular output line from ng serve is held back, like it's no longer sent in the Stardard Output stream. The WaitForMatch method hits his timeout after 5 seconds and is catched from the code of the WithTimeout extension method, that outputs the (bugged) "... 0 seconds ..." message.

For what I could see, once you dotnet run your application, a series of processes is spawn in sequence, but i couldn't notice any difference in the command lines from Angular 8 to Angular 9.

My theory is that something has been changed in Angular CLI that prevents that line to be sent in stdout, so the .net proxy doesn't catch it and can't detect when the angular server is started.

As per this issue:

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

proposed solutions are to set progress: true in angular.json or perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).

Here is what I did

from Fairlie Agile, commented out this line in main.ts

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

From Claudio Valerio In angular.json , set

"progress": true,

Now I can run the app by clicking on F5 / Run IIS Express

Related