Search code examples
angularrestlocalhosthttp-status-code-404angular-httpclient

Angular http.get returns 404 in app but ok from POSTMAN


I am trying to test an API call. I am able to make it work from POSTMAN. When I try writing a simple Angular app to get the result, I am getting errors.

From looking at the errors, it seems like it is either appending localhost onto the actual domain, or its leaving it off but also leaving off the parameters. Why are the URLs formed differently in the first error versus the second? Why am I getting 404 errors from the app but the url works in POSTMAN?

I am getting the following errors when running ng serve for this application

  1. GET http://localhost:4200/subdomain.domain.com/api/api/UserAccount/FindUser?firstName=John&lastName=Doe&dob=1/1/1981&locale=en&optionEmailForTesting= 404 (Not Found)

  2. Backend returned code 404, body was:

    Cannot
    GET
    /subdomain.domain.com/api/api/UserAccount/FindUser

I tried altering the format of the URL in multiple ways but none of them affected the end result.

app.component.ts:

export class AppComponent implements OnInit {
  title = 'helloWorld bro';
  private apicallsService : ApiCallsService;

  constructor(acs: ApiCallsService) 
  { 
    this.apicallsService = acs;
  }

  ngOnInit() {
    this.apicallsService.FindUser().subscribe(resp => { console.log(resp); });
  }

}

apicalls.service.ts:

@Injectable()
export class ApiCallsService
{
    constructor(private http : HttpClient ) { }

    public API_URL: string = 'subdomain.domain.com/api';

    public FindUser():Observable<ResponseDTO>
    {
       // let mail = (optionEmailForTesting != undefined) ? optionEmailForTesting : "";

        let url = this.API_URL + '/api/UserAccount/FindUser';    
        const params = new HttpParams()
            .set('firstName', 'John')
            .set('lastName', 'Doe')
            .set('dob', '1/1/1981')
            .set('locale', 'en')
            .set('optionEmailForTesting', '')

        return this.http.get<ResponseDTO>(url,{params}).pipe(
        catchError(this.handleError)
        )
    }
}

Solution

  • You need to add the protocol to the start of the url, ie.

    public API_URL: string = 'http://subdomain.domain.com/api';
    

    Without this, HttpClient treats the url as relative.