Search code examples
postcors

Can't send requests other than GET from my browser to a Spring application on localhost


I can't send POST requests from my browser to a Spring application running on localhost.

I can send GET requests, and my POST and PUT requests are answered as if they are GET requests.

<html>
<body>
<button onclick="sendPostRequest()">Send POST Request</button>
<script>
function sendPostRequest() {
  fetch('http://localhost:8080/endpoint', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ key: 'value' }) 
  }).then(response => console.log(response));
}
</script>
</body>
</html>

Solution

  • If you open the Firefox Developer Tools (F12) in Firefox and go to the Network tab you can see the request when pressing the button.

    In the transferred column you see: "CORS Missing Allow Origin".

    enter image description here

    The fix is simple; create a new class in Java:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH")
                    .allowedHeaders("*");
        }
    }
    

    Nota bene: this is useful for local testing, but if you want to push to prod you need a proper CORS configuration!