0

I am trying to call an API at localhost:3000/rooms. So I created a file named proxy.config.json inside the src folder like this:

{
    "/rooms": {
      "target": "http://localhost:3000",
      "secure": false
    }
}

I also changed this code in angular.json too:

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          
          "configurations": {
            "production": {
              "browserTarget": "HotelManagement:build:production"
            },
            "development": {
              "browserTarget": "HotelManagement:build:development",
              "proxyConfig": "src/proxy.config.json"
            }
          },
          "defaultConfiguration": "development"
        }

The api is made in Mockoon and gives an array of rooms. When I call it from browser normally it gives correct output but in angular. It's not getting called. I don't want to set a local variable in service saying localhost:3000 because then it will give me a CORS problem and also it's not a good practice (someone said).

Well, this is my Service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class RoomsService {

  getRooms(): Observable<any>{
    console.log("Calling Get...")
    return this.http.get('/');
  }

  constructor(private http:HttpClient) { }
}

The errors are as following: error

I even tried making it http.get.get('/rooms') but that's absurd I guess because it's always calling it on localhost:4200 (where angular is running).

What do I do now??

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Thug Life
  • 87
  • 10
  • What if you add `"changeOrigin": true` to the `angular.json` after the `secure` property. – SwissCodeMen Jul 24 '23 at 21:36
  • And how do you start your angular application? Otherwise look at the [official documentation](https://angular.io/guide/build#proxying-to-a-backend-server) about proxy from angular or from this [answer](https://stackoverflow.com/a/71764796) – SwissCodeMen Jul 24 '23 at 21:50

0 Answers0