3

I'm setting up CORS in spring with:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowedMethods("GET","POST","PUT","DELETE", "OPTIONS");
        }
    };
}

This works for all endpoints and error handlers, but not the 404 handler. I have the properties set to make sure that spring throws an exception when handler not found, so I would think it would be handled the same way as other exceptions

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

I get this response from the fetch call in browser:

OPTIONS http://localhost:8080/badEndpoint 404 ()
localhost/:1 Fetch API cannot load http://localhost:8080/badEndpoint. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any ideas why the CORS headers are not being applied on the 404 handler?

theUnicycleGuy
  • 145
  • 2
  • 11
  • It's moot, right? What would be the point of allowing the request via CORS if there's nothing at that address? The spec seems to indicate that the network error steps are used for responses out of the 2XX range, which would certainly include a 404. https://www.w3.org/TR/cors/#simple-cross-origin-request-0 – unigeek Aug 04 '17 at 21:09
  • 1
    Fair point. It's just that the javascript fetch api rejects a request with no CORS headers, whereas a simple 404, or 503 or whatever else would be considered successful and the code handles the responses from there. The way my code is structured, I handle error responses from the server differently than network problems. So a timeout or a CORS issue cause an exception, whereas 404s, 500s etc fall into a serverErrorHandler – theUnicycleGuy Aug 09 '17 at 23:43

0 Answers0