Tuesday, July 28, 2020

set Access-Control-Allow-Origin header in spring web

Your got a normal spring rest resources like the following,
    @GetMapping("/client")
    public Client getClient(@RequestParam(value = "id", defaultValue = "1") String id) {
        logger.debug("/client requested with parameter {}", id);
        return clientHandler.handle(id);
    } 
then your wrote a html file like the following,
demo>cat jquery.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("http://localhost:8080/client?id=1", function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>
demo>

Next you test it with chrome


hoops, what's the error mean?

Access to XMLHttpRequest at 'http://localhost:8080/client?id=1' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Ajax has a same origin rule to prevent javascript to modify DOM across domain.
Since your html is located in a static file instead of served by a web server, the origin is null in the request issued by jquery.

To "fix" it and continue to test local, we need to relax the same origin rule. Spring allows developer to do that with an extra annotation. Modify your resource like the following:

import org.springframework.web.bind.annotation.CrossOrigin;
...
    @CrossOrigin
    @GetMapping("/client")
    public Client getClient(@RequestParam(value = "id", defaultValue = "1") String id) {
        logger.debug("/client requested with parameter {}", id);
        return clientHandler.handle(id);
    } 

restart the server, now, try that jquery click function, it now ok:



There is a dedicated article I wrote about http client and server in depth, more information can be found there.




No comments:

Post a Comment

meta.ai impression

Meta.ai is released by meta yesterday, it is super fast you can generate image while typing! You can ask meta.ai to draw a cat with curvy fu...