Home > database >  How to avoid the problem of CORS in Angular and Spring boot project?
How to avoid the problem of CORS in Angular and Spring boot project?

Time:03-22

I've actually crate an angular service to get data from the server which running on 'localhost:8080/' (endpoint /user) . But when I serve the angular project on 'localhost:4200' it made this Error :Access to XMLHttpRequest at 'localhost:8080/user' from origin ..

I tried to solve this problem by adding @CrossOrigin(origins = "*") in the controller and I add a proxy.conf.json in the angular project like I found here : 'https://angular.io/guide/build' But the problem persist .

this is the angular service :

  @Injectable({
  providedIn: 'root'
})
export class RestService {
  api = 'localhost:8080/user'
  constructor(private http: HttpClient) { }
  getUsers(): Observable<String> {
    return this.http.get<String>(this.api);
  }
}

this is my proxy.conf.json :

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

this is the conf in angular.json :

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "crud:build",
            "proxyConfig": "src/proxy.conf.json"
          }

and this is the spring boot controller :

@RestController
@CrossOrigin(origins = "*")

public class userController {
    @GetMapping("/user")
    public String getuser(){
        return "the user name is bilel" ;
    }
}

CodePudding user response:

To build onto @Alain Boudard's answer, you need to add a path rewrite:

export class RestService {
  baseUrl = 'api/user'

  constructor(private http: HttpClient) { }

  getUsers(): Observable<string> {
    return this.http.get<string>(this.baseUrl);
  }
}

and the in the proxy.conf.json file, don't forget the pathRewrite so that 'api' is deleted from the URL before the call is made to the backend:

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

PS: By the way, you will very rarely need to use type String, instead use the primitive string (lowercase s): https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html

CodePudding user response:

You would not want to tell your Angular service about the target server and its port, it's against the use of the proxy conf.

Call something like a generic api/ root endpoint and map it :

export class RestService {
  api = '/api/user'
  constructor(private http: HttpClient) { }
  getUsers(): Observable<String> {
    return this.http.get<String>(this.api);
  }
}

And the proxy like that :

{
    "/api": {
        "target": "http://localhost:8080",
        "secure": false
    }
}
  • Related