Home > front end >  Angular 14 with spring-boot backend CORS issue
Angular 14 with spring-boot backend CORS issue

Time:07-29

I have an angular application which is running on my notebook at http://localhost:4200 I have a Java backend server where placed some rest api.

I am trying to call a simple GET method on the java backend but I always get CORS error.

Access to XMLHttpRequest at 'http://javabeckendserver:8060/pbackend/api/sa/tasktypes' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I read this article https://angular.io/guide/build and I have followed the proxy configuration, but the error message is the same.

So I have created proxy.conf.json file with this content:

{
  "/pbackend/*": {
    "target": "http://javabeckendserver:8060",
    "secure": false,
    "logLevel": "debug"
  }
}

I configured it in angular.json file at serve tag as an option:

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

Update: I use a Http Interceptor to add more property to the http request header this way:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let customAuthType = this._tokenService.hasToken() ?  'Bearer '.concat(this._tokenService.getToken()): 'Basic ****';

    const headers = request.headers.set('Authorization', customAuthType)
                                   .set('Content-Type', 'application/json');
    return next.handle(request.clone({ headers }));
}

At the '****' has normal Base64 encoded string.

And here my method at the backend side:

    @PreAuthorize("hasRole('ROLE_TASK_TYPE_READER')")
    @GetMapping("/tasktypes")
    public ResponseEntity<List<TaskTypeDto>> findAllTaskType() {
        log.info(">> findAllTaskType()");
        return ResponseEntity.ok(taskTypeService.findAll());
    }

I have tested with postman the REST API and it worked fine as expected but not from Angular app.

what have I done wrong?

CodePudding user response:

Since both the services (Angular and backend java) are running on 2 different port numbers, the request coming from Angular to java will be considered as an external one. As the error message says "No 'Access-Control-Allow-Origin' header is present on the requested resource" I would advice you to annotate your java side controller with @CrossOrigin and see if your API request from Angular gets served.

More details about CrossOrigin can be found here - CrossOrigin

  • Related