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:
- 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---
- 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