Home > Software design >  springboot rest api how to answer to a preflight request sent by the CORS
springboot rest api how to answer to a preflight request sent by the CORS

Time:08-01

I'm developing a webapp angular-springboot with some other people, and to a few of those certain requests of the app are blocked by the cors with this error:

Access to XMLHttpRequest at 'https://localhost:8443/api/contratto/update' 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

so I have researched what a preflight request is and I've added this method to the controller:

@RequestMapping(value = "/update",method = RequestMethod.OPTIONS)
    public ResponseEntity<String> preFlightHandler(){
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Access-Control-Allow-Origin", 
          "https://localhost:8443");

        return ResponseEntity.ok()
          .headers(responseHeaders)
          .body("gggg");
    }

but it never even gets executed, how do I create a method mapped specifically for preflights?

CodePudding user response:

didn't make a method mapped for that but I solved the error, Im' using the WebSecurityConfigurerAdapter and in the method configure(HttpSecurity http) I added the line http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());

CodePudding user response:

I have backend API which was accessible with GET, but couldn't be successful with POST, due to PREFLIGHT issue, which incurred CORS blockage.

Thus, in this site, https://newbedev.com/http-request-from-angular-sent-as-options-instead-of-post#:~:text=HTTP request from Angular sent as OPTIONS instead,is allowed from a particular domain as follows:

I have found that, you just simply play with OPTIONS method, which your browser calls to backend for before "ACTUAL" call. this is called Preflight request.

It uses OPTIONS method instead of get/post/put. Thus, this might be of help.

If you use Node Js Server:

 if (req.method == "OPTIONS")
    {
        res.writeHead(200, {"Content-Type": "application/json"});
        res.end();
    }

With PHP, I use this code:

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("HTTP/1.1 200 ");
exit;
}

These are my headers in PHP:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("HTTP/1.1 200");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With, Origin");

Note the OPTIONS method in the headers.

If you use other language, that might be easy for you using this concept.

That's it.

  • Related