Search code examples
javaangularcorshttpclienthttpserver

Angular 9 (HttpClient) How to fix CORS error?


I have POST request:

getLagTimestamp() {
    const headers = new HttpHeaders({
      'Access-Control-Allow-Origin': '*', 'Authorization': 'Basic YWRtaW46cGFzc3dvcmQ='
    });
    this.response = this.http.post(this.url, '{"method":"topics_lag","id":"req-id-01","jsonrpc":"2.0"}', {headers:headers})
      .subscribe((response) => {
        this.response = response;
        this.lagTimestamps = Object.setPrototypeOf(this.response, Array<LagTimestampObject>());
        console.log(this.lagTimestamps);
      });
  }

And I have backend on Java with com.sun.net.httpserver.HttpsServer and Authentication. On backend I set paremeters:

    httpExchange.getResponseHeaders().add("Content-Type", "application/json");
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
    httpExchange.getResponseHeaders().add("Content-Type", "application/json");
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token,Authorization");
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");

but i have some problems with requests between frontend and backend:

Access to XMLHttpRequest at 'http://localhost:9099/rpc' 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.

enter image description here

enter image description here

I tried using proxy for frontend like this:

{
  "/rpc": {
    "target": "https://localhost:9099",
    "secure": true,
    "pathRewrite": {
      "^/rpc": ""
    },
    "changeOrigin": true
  }
}

I have been trying to solve the problem for a week now, but no action helps. How to solve this problem?

thanks

addition: after updating on the backend:

if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
   httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
   httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
    httpExchange.sendResponseHeaders(200, -1);
}

I have: enter image description here


Solution

  • You need the preflight response (the OPTIONS call response) to return the "Access-Control-Allow-Origin", "*".

    You are getting a 401 unauthorized from your server for the options call. Look at allowing the options call and returning the header "Access-Control-Allow-Origin", "*" here.