Angular sends XHR requests only when necessary, minimizing unnecessary HTTP requests

I am currently working on a project with a frontend developed in Angular and a backend using Java EE. The main issue I am facing is that while the backend expects a standard Http request, the Angular HttpClient sends XHR requests instead. This has triggered the following error: https://i.sstatic.net/cNhb4.png

I believe I have two possible solutions:

  1. One option would be to update the backend to allow CORS access-control-allow-origin. However, implementing this change would require me to find out how to make such modifications and whether I have the permission to do so. ---OR---
  2. The second option involves modifying the frontend to send an Http request rather than XHR.

As I have control over the frontend code and can easily edit it, I am inclined towards pursuing the second option.

Below is the service responsible for sending the Get request:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { Survey } from './survey';
import { HttpErrorHandler, HandleError } from '../http-error-handler.services';

import { environment } from '../../environments/environment';


@Injectable({
  providedIn: 'root'
})
export class SurveysDisplayService {

  surveysURL=environment.baseUrl+'api/surveys/';
  private handleError: HandleError;
  
  constructor(
    private http: HttpClient, 
    httpErrorHandler: HttpErrorHandler) {
      this.handleError = httpErrorHandler.createHandleError('DisplayService');
     }

     //retrieve surveys from server
     getSurveys(): Observable<Survey[]>{
      return this.http.get<Survey[]>(this.surveysURL)
      .pipe(
        catchError(this.handleError('getSurveys', []))
      );
     }

}

And here is the component.ts file that utilizes the service:

import { Component, OnInit } from '@angular/core';

import { Survey } from './survey';
import { SurveysDisplayService } from './surveys-display.service';

@Component({
  selector: 'app-survey',
  templateUrl: './surveys-display.component.html',
  providers:[SurveysDisplayService],
  styleUrls: ['./surveys-display.component.css']
})
export class SurveysDisplayComponent implements OnInit {
  surveys:Survey[]=[];


  constructor(private surveysDisplayService:SurveysDisplayService) { }

  ngOnInit(): void {
    this.getSurveys();
  }

  getSurveys(): void {
    this.surveysDisplayService.getSurveys()
      .subscribe(surveys => (this.surveys=surveys));
  }

}

Additional information regarding my Angular version can be found here: https://i.sstatic.net/KhMHw.png

Answer №1

The issue at hand is that you require CORS headers from the server, but are unable to make it send them. One solution could be to utilize a proxy that handles this task for you. One suggestion is using HAProxy, and below is a snippet from a blog post that demonstrates how to achieve this:

listen http-in
    mode http
    listen *:80

    # Add CORS headers when Origin header is present
    capture request header origin len 128
    http-response add-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found }
    rspadd Access-Control-Allow-Headers:\ Origin,\ X-Requested-With,\ Content-Type,\ Accept  if { capture.req.hdr(0) -m found }

Alternatively, nginx can also serve as a solution (albeit slightly more complex to configure). You can refer to an example configuration here.

Answer №2

To enable CORS access-control-allow-origin on the backend, some adjustments need to be made which I must investigate and see if I have the authority to modify the backend settings.

This action is necessary for proper functionality.

Another solution provides different options, but creating a new backend that serves as a proxy might be the most viable route if backend access is restricted.


Adjust the frontend to utilize Http requests instead of XHR.

XHR represents an API for making HTTP requests using JavaScript; it does not signify a distinct request type.

If opting for a non-XHR approach, one would need to implement regular form submissions or links, resulting in a complete page reload and potentially undermining the efficiency of Angular.

This shift would also necessitate modifications to the backend so that it delivers a fresh HTML document.

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

Obtaining JSON Data from API using Angular 2 Http and the finance_charts_json_callback() Callback

Having trouble retrieving JSON data from this API: I'm unsure how to access the returned finance_charts_json_callback(). Currently, I am utilizing Angular 2's http.get(): loadData() { return this.http .get(this.url) .map((res) => ...

A guide on simulating mouse events in Angular for testing Directives

I am currently exploring the functionality of a column resizable directive that relies on mouse events such as mouseup, mousemove, and mousedown. resize-column.directive.ts import { Directive, OnInit, Renderer2, Input, ElementRef, HostListener } from "@a ...

Retrieve a CSV file from the server using Angular and JavaScript

How can a visitor download a CSV file from the server using Angular 7? Many websites suggest creating a CSV file dynamically from data and then using blob creation for downloading. However, I already have the CSV file on the server and want to directly do ...

Ways to coordinate two Angular Material pagination components

On my design page, I have two paginators that are not synchronized when added. If you are facing this issue, check out https://material.angular.io/components/paginator Here is a link to an example showcasing the issue: https://plnkr.co/edit/w5ZuXnfIgmKW1 ...

TypeScript, express framework, node-dev tool, and a personalized file type loader

Looking to create a node.js server with Express and TypeScript, while also wanting the ability to auto-restart or hot-reload during development as I make changes. Additionally, I need the capability to import custom file types. While Webpack can handle so ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Enhancing the selection of options in Angular 2 using object values

When I retrieve a list of object values from an API, each object contains a property to identify the selected item. I am successfully binding the items list to the view. Here is the JSON data: https://i.sstatic.net/itmfh.png Below is my code snippet: & ...

Protractor end-to-end tests fail to run properly when the `--spec` flag is utilized

Currently, I am running 'ng e2e' on an Angular CLI project and I am looking to specify a specific test to run instead of running all of them. When I execute ' ng e2e --aot ', the test runs smoothly. However, when I try ' ng e2e ...

Extract nested values within objects and arrays, and return the complete type of the original object

I have a dataset that resembles the structure of IconItems: { title: "Category title", description: "Example description", lists: [ { id: "popular", title: "Popular", items: [ { ...

Dynamically determine the length of an array using Typescript

Can the length of an array be determined based on a numerical variable? For example: func(1); // outputs [string] func(2); // outputs [string, string] func(5); // outputs [string, string, string, string, string] ...

Is it possible to create models that can be used in both Node.js and angular without duplication

Currently, I am diving into the world of Node.js and Angular (part of a MEAN project) through an online course on Udemy. One challenge I have encountered is the need to create identical models for both the back-end and front-end (specifically with angular2 ...

Tips for accessing and modifying local files in Angular 2

Is there a method in Angular 2 to access files from an absolute path? I have utilized the 'filesaver' library for file saving, storing the files locally in txt/json formats. For instance: let blob = new Blob([document.getElementById(&apos ...

Struggling to figure out webhooks with Stripe

I have encountered a strange issue while using Stripe webhooks to process payments on my website. When I set the currency to USD, it prompts me to provide an address outside of India, which is expected. However, when I change the currency to INR, the addre ...

Easily transferring sessionStorage values between components in Angular

I am looking for assistance on storing a user ID in sessionStorage and retrieving it in a blog component. Can anyone guide me on how to achieve this? LoginComponent.ts import { Component, OnInit } from '@angular/core'; import { Router, Activate ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

errors.ts:30 ERROR Error: Unhandled promise rejection: Error: No routes found for specified URL Segment: 'products,%20productId'

I'm in the process of learning Angular by following a tutorial on a website. You can find it here: https://angular.io/start/routing Everything is going smoothly so far, except for the section on routing. If I add 'products/1' to the end of ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

Error message: TypeScript: Attempting to access a value from an enum results in an implicit 'any' error for the element

I'm striving to achieve the most precise solution for this issue. I have a parameter that can be a number or a valid string, and I am utilizing it as an index to retrieve the value of a declared enum. Due to Typescript's lack of knowledge about ...

Is it possible to use a type predicate to return `void` from a function?

When creating data validation APIs, I have a common approach where I include two functions - one that returns a boolean value and another that throws an error. The throwing function typically has a void return type. interface MyType { numberField: num ...