1
votes

I have an Angular + Spring Boot project. The Angular project contains services making Http requests to Spring Boot app running on port 8080. Strangely, at least one of my services is making Http calls to localhost:4200 instead of localhost:8080 even though I think I've set up proper configuration.

Angular Service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Housing } from '../_models/housing';
import { Observable, of } from 'rxjs';
import {catchError} from 'rxjs/internal/operators';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'jwt-token',
    'Access-Control-Allow-Origin': '*'
  })
};
@Injectable({
  providedIn: 'root'
})

export class HousingService {

  housingList: Housing[];

  constructor(private http: HttpClient) {}

  getAll() {
    return this.http.get<Housing[]>('/api/v1/housing/getAllHousing');
  } 
  getHousingById(id) {
    return this.http.get<Housing>('/api/v1/housing/getHouseById/' + id);
  }
  fetchData(id): Promise<Housing>{
    const promise = this.http.get<Housing>('/api/v1/housing/getHouseById/' + id).toPromise();
    return promise
  }
  addHousing(housing: Housing): Observable<Housing>{
    return this.http.put<Housing>('/api/v1/housing/addOrUpdateHouse', housing, httpOptions)
  }
  enableOrDisableHouseById(id: String){
    return this.http.put<Housing>('/api/v1/housing/enableOrDisableHouseById/'+ id, httpOptions)
  }
  deleteHousing(id): Observable<Housing>{
    return this.http.delete<Housing>('/api/v1/housing/deleteHouseById/' + id, httpOptions)
  }
}

proxy.conf.json file at the root of the project :

{
    "/api/*": {
       "target": "http://localhost:8080/",
       "secure": false,
       "changeOrigin": true,
       "logLevel": "debug"
    }
 }

I am launching my Angular server with following command : ng serve --proxy-config proxy.conf.json

Error message : Error message

1
why you dont use this? this.http.get<Housing[]>('localhost:8080/api/v1/housing/getAllHousing'); - behroozbc
@behroozbc I don't want to do that because I am sure there is a better way of doing it rather than putting the base url in every single Http call - bretondev
did you add you proxy config to angular.json? - Vlad Mamaev

1 Answers

0
votes

You can configure your webpack proxy which will forward your request to the appropriate location.

  devServer: {
    ...
    proxy: {
       '/api/v1': 'http://localhost:8080',
    } 
  }