Home > Blockchain >  Invalid CORS on Angular 12 with Java Spring Boot
Invalid CORS on Angular 12 with Java Spring Boot

Time:10-21

I have an angular application that uses a proxy to access the java spring boot backend and other services:

proxy.conf.js:

const PROXY_CONFIG = [
  {
    context: [
        "/my/api/context/**"
    ],
    target: "http://localhost:9000/",
    headers: {
        "Content-Type": "application/json"
    },
    secure: false,
    logLevel: "debug",
    changeOrigin: true,
  },
  ...
}]

module.exports = PROXY_CONFIG;

MyController.java:

@RestController
@RequestMapping("/my/api/controller/path")
public class MyController {
    ...
    @PostMapping("/endpoint/{id}")
    public ResponseEntity<Boolean> endpoint(@PathVariable Long id) {
        ...
    }
    ...
}

I'm also using zookeeper for some environment configurations.

The issue is that for GET requests, my angular application works fine but for any other verb, I get a 403 Forbidden error and a Invalid CORS request message from spring boot. What's weird is that when I copy the request with all the headers and submit via Postman, I get a 200 response with no problems.

There are many questions regarding this problem on the web but all seem to point to a backend issue. In this case the backend seem to be well configured (the Postman request is successful).

I'm sure I'm missing something trivial but just can't put my finger on it. Anyone has any idea what could be going wrong here? Any help or suggestion would be appreciated. If you need anything else, just let me know and I'll see if I can share.

EDIT #1:

my.service.ts:

myPost(id: number): Observable<any> {
  return this.http.post<any>(`${this.endpoint}/${id}`);
}

CodePudding user response:

Just add

@CrossOrigin

On your controller class and it should solve the issue.

CodePudding user response:

I just had to set:

changeOrigin: false,

And it worked.

  • Related