Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...\dist\fxcore\server\main.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or npm run build:ssr && npm run serve:ssr, my application now fails to open, displaying a NetworkError response in the console. The error seems to be related to the excessive number of HTTP requests sent through the class 'constructors(){..}'. Despite researching various solutions, I am unable to pinpoint where I may have gone wrong. It's worth noting that my backend is built on nodejs and express. Any guidance on this matter would be greatly appreciated. Below is an example of the complete error response consistently appearing in the console:

ERROR NetworkError
    at XMLHttpRequest.send (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:200768:19)
....
...

Answer №1

After struggling with a persistent error for days, I stumbled upon an article that explained how to implement a relative to absolute interceptor. If you're facing a similar issue, check out the link below:

  1. I created a file named "universal-relative.interceptor.ts" in my src folder.
  2. I added the interceptor code to the "universal-relative.interceptor.ts" file.
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { REQUEST } from '@nguniversal/express-engine/tokens';
import { Request } from 'express';

// case insensitive check against config and value
const startsWithAny = (arr: string[] = []) => (value = '') => {
    return arr.some(test => value.toLowerCase().startsWith(test.toLowerCase()));
};

// http, https, protocol relative
const isAbsoluteURL = startsWithAny(['http', '//']);

@Injectable()
export class UniversalRelativeInterceptor implements HttpInterceptor {
    constructor(@Optional() @Inject(REQUEST) protected request: Request) {}

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        if (this.request && !isAbsoluteURL(req.url)) {
            const protocolHost = `${this.request.protocol}://${this.request.get(
                'host'
            )}`;
            const pathSeparator = !req.url.startsWith('/') ? '/' : '';
            const url = protocolHost + pathSeparator + req.url;
            const serverRequest = req.clone({ url });
            return next.handle(serverRequest);
        } else {
            return next.handle(req);
        }
    }
}
  1. In your "app.server.module.ts" file, locate and open it.
  2. Add the following snippet of code into your app server module.
import { NgModule } from '@angular/core';
import {
  ServerModule,
  ServerTransferStateModule,
} from "@angular/platform-server";

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { UniversalRelativeInterceptor } from 'src/universal-relative.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  imports: [AppModule, ServerModule, ServerTransferStateModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: UniversalRelativeInterceptor,
      multi: true,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

By following these steps, I was able to successfully resolve the error that had been plaguing me for days!

Answer №2

I encountered the dreaded ERROR NetworkError, but fear not - I discovered a workaround to eliminate this pesky error for good. This solution is particularly valuable as it addresses the exact same issue mentioned earlier. If my experience can assist others facing similar server errors, then I am delighted.

When making an API request to the server during a reload event, remember to first verify isPlatformBrowser when utilizing ng-universal. Here's an example:

import { Component, OnInit, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { HttpClient, HttpHeaders } from '@angular/common/http';

export class HomeComponent implements OnInit {

  public testBrowser: boolean;
  public data: any;
  
  constructor(private http: HttpClient, @Inject(PLATFORM_ID) platformId: string) {
    this.testBrowser = isPlatformBrowser(platformId);
  }

  ngOnInit() {
    if (this.testBrowser) {
      //avoid server NETWORK error
      this.data = this.http.get('/api');
    }
  }
}

I also faced this same challenge of encountering errors while attempting server calls from the client without verifying isPlatformBrowser === true. By implementing this check within OnInit, my problem was resolved. Hopefully, this insight can help address this bug effectively.

This solution proved instrumental in overcoming a persistent bug that had been plaguing me. You can find more details here:

Answer №3

I encountered a similar error message. To resolve it, consider removing the TransferHttpCacheModule from your app.module and instead create a custom HTTP transfer interceptor file.

In my case, I created a file named transfer-state.interceptor.ts and then included it in the providers:[] section of my app.module to address the issue. Below are examples illustrating how I implemented this solution. While I cannot guarantee that this method will work for everyone, it did eliminate the error for me.


//app.module.ts

import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";

import { AppRoutingModule } from './app-routing/app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './modules/home/home.component';
import { SliderComponent } from './components/slider/slider.component';
import { WindowRefService } from './services/window-ref.service';
import { TransferStateInterceptor } from './interceptors/transfer-state.interceptor';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    SliderComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    BrowserTransferStateModule,
    AppRoutingModule,
    HttpClientModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    WindowRefService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TransferStateInterceptor,
      multi: true
    }
],
  bootstrap: [AppComponent]
})
export class AppModule { }

If the above custom transfer state file does not work for you, there may be alternative approaches available.


//transfer-state.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { Observable, of } from 'rxjs';
import { StateKey, TransferState, makeStateKey } from '@angular/platform-browser';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { tap } from 'rxjs/operators';

@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {

  constructor(
    private transferState: TransferState,
    @Inject(PLATFORM_ID) private platformId: any,
  ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // For this demo application, we will only worry about State Transfer for get requests.
    if (request.method !== 'GET') {
      return next.handle(request);
    }


    // Use the request url as the key.
    const stateKey: StateKey<string> = makeStateKey<string>(request.url);

    // For any http requests made on the server, store the response in State Transfer.
    if (isPlatformServer(this.platformId)) {
      return next.handle(request).pipe(
        tap((event: HttpResponse<any>) => {
          this.transferState.set(stateKey, event.body);
        })
      );
    }

    // For any http requests made in the browser, first check State Transfer for a 
    // response corresponding to the request url.
    if (isPlatformBrowser(this.platformId)) {
      const transferStateResponse = this.transferState.get<any>(stateKey, null);
      if (transferStateResponse) {
        const response = new HttpResponse({ body: transferStateResponse, status: 200 });

        // Remove the response from state transfer, so any future requests to 
        // the same url go to the network.
        this.transferState.remove(stateKey);
        return of(response);
      } else {
        return next.handle(request);
      }
    }
  }
}

To implement custom caching, you can explore using memory-cache, although I have not personally tested this option. Additionally, the following articles provided valuable insights during my troubleshooting process:

If needed, ensure to include ServerTransferStateModule in your app.server.module file.


//app.server.module

import { NgModule } from '@angular/core';
import {
  ServerModule,
  ServerTransferStateModule
} from "@angular/platform-server";

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

Best of luck with your implementation!

Answer №4

One issue I encountered was that my API variable was undefined due to the Angular SSR life-cycle. The data only became available after the browser module had loaded.

I had been employing a similar approach:

this.isBrowser$.subscribe(isBrowser => { ... });

in order to configure the correct api endpoint.

Answer №5

While investigating the original problem, I discovered that the root cause in my scenario was due to the resourceUrl variable not being an absolute path for the production environment.

environment.ts

export const environment = {
  resourceUrl: 'http://localhost:8082/api/site',
  siteId: '1111'
};

During development, I had been using an absolute URL "http://localhost:8082/api/site" for the resourceUrl environment variable, which worked fine in that mode.

environment.prod.ts

export const environment = {
  resourceUrl: '/api/site',
  siteId: '1111'
};

However, in production mode, the relative URL "/api/site" caused issues when running "serve:ssr".

return this.http.get<ISomething>(`${environment.resourceUrl}/home/${environment.siteId}`);

To resolve this issue, I updated environment.prod.ts to use an absolute URL instead of a relative one.

I am sharing this response as a reminder in case others overlook David's comment. Thank you, David.

Answer №6

If you happen to encounter an issue while utilizing ng-universal, and the error stems from server side rendering, a straightforward solution is to add the following code snippet:

    if (typeof window === 'object') {
      // your client side httpClient code
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

`Erase content from a field once text is typed into a different field`

I have a Currency Converter with two input fields and a button. I enter the amount to be converted in the first field, and the result of the conversion appears in the second field. My question is: How can I automatically clear the second field when I type ...

"Encountering a 404 Error when attempting to refresh an Angular 13 application hosted on an Apache

I have developed a prototype web application and now need to deploy it on an Apache server running Ubuntu OS. After building the web app, I hosted it on my local machine for testing purposes. I have configured the .htaccess file as follows: RewriteEngine ...

Angular: merging object values into a single string by looping over them

i am dealing with the following data : "commercialRanges": [ { "rangeId": "700", "rangeName": "POSTPAID" }, { "rangeId": "500", "rangeName": "PREPAID" }, ] In my view, I am aiming to display the ...

Creating a custom design for legends in Chart.js

I'm currently working on a project using chart.js and I'm trying to customize the label/legend styling for my chart. My goal is to replace the rectangular legend with a circular one. I've come across the suggestion of creating a custom legen ...

Alert: Refs cannot be assigned to function components. Any attempt to access this ref will result in failure. Have you considered using React.forwardRef()? displayed in the @Mui Component

Is anyone familiar with this particular component? <Controller control={control} {...register("DOB", {})} render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

Is it possible to establish a scope for jquery.ajaxSetup()?

Currently, I am working on a project involving numerous ajax calls with repetitive parameters. After some consideration, I am contemplating using jquery.ajaxSetup() to streamline the code. However, jQuery does not recommend this approach in their API docu ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

Using the foreach Loop in Javascript and AngularJs

Having trouble with a foreach loop because you're not sure of the column name to access specific data? Here's a solution to display all columns along with their corresponding data: angular.forEach(data, function(value, key) { console.log( &a ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

The visibility of content that flickers on the webpage should be hidden with the display: none property during loading

Currently working on a new toy website, but encountering some unexpected behavior. On the homepage HTML file, there are two separate sets of <body> tags: <body class = "intro">...</body> <body class = "home">...</body& ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...

Using Vivus.js in an Angular 5 Component

I am currently facing some challenges while attempting to incorporate Vivus.js library into Angular 5. The issue seems to be arising from the constructor of Vivus, which suggests that the library is being loaded correctly but not recognizing my element id. ...

An error occurred: TypeError - Unable to access the 'value' property of a null object during a value change

Example ImageCreating a dynamic form where rows and select box options are added dynamically using 'x' and 'i' increment values in two JavaScript functions. The code works fine when the option selected is 0.5, but throws an error Uncaug ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

What steps should I take to incorporate a timer into my bot similar to the timer used by other giveaway bots

I am looking to add a timer to my bot giveaway embed message that continues to update itself even when the bot is offline, without showing that the message was edited. Here's what I currently have in my embed: const embed = new MessageEmbed(); ...

Having trouble showing a leaflet map on Node.js Express with Jade

As a newcomer to this technology, I'm currently following a tutorial here. My goal is to generate a map view using jade (although I understand it's now called pug). Within my index.js file, I have set up a router request for the map page. This r ...