I have a frontend in Angular and the backend is Java EE. The issue I am running into is that the backend is expecting a standard Http request but Angular HttpClient sends XHR. I get this error:
I think the two options I have are
- somehow update the backend to allow CORS access-control-allow-origin which I would have to figure out how to do and assuming that I have the option to make changes to the backend ---OR---
- change the front end to send an Http request and not XHR.
Since I am writing the frontend and can easily manipulate it, this is the option I am shooting for.
Below is the service 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 that uses 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));
}
}