Spring Global CORS-Konfiguration nicht funktioniert, aber Controller-Ebene config nicht

Ich versuche zu konfigurieren CORS weltweit über WebMvcConfigurerAdapter unten dargestellt. Um zu testen, ich bin schlug meinen API-Endpunkt über einen kleinen Knoten app, die ich erstellt zum emulieren eines externen Dienstleisters. Wenn ich versuche, diesem Ansatz die Antwort enthält nicht die korrekten Header und schlägt mit

XMLHttpRequest cannot load http://localhost:8080/api/query/1121. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:333' is therefore not allowed access.

Global Config

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/query/**")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
}

Wenn ich mir jedoch nutzen die @CrossOrigin annotation wie also funktioniert es ganz gut reagiert mit dem richtigen Header.

@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/query", produces = MediaType.APPLICATION_JSON_VALUE)
public class QueryController {
   ......
}

Produziert

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:333

Was bin ich, um die Globale config-Arbeit (folgte den Anweisungen hier https://spring.io/blog/2015/06/08/cors-support-in-spring-framework). Ich fühle mich wie ich bin etwas fehlt einfach, da die Notierung der controller funktioniert Prima.

  • Vielleicht .allowedOrigins("*").allowedHeaders("*") sind überflüssig in der globalen Konfiguration
  • Hast du es herausfinden? Ich bin auch mit diesem Problem. Versucht, Antworten aber nicht Arbeit für mich...
  • Ich war im selben Boot wie du, aber geschafft, etwas zu bekommen, zu arbeiten. Haben Sie einen Blick auf meine Antwort hier: stackoverflow.com/a/55629589/5877810
InformationsquelleAutor Adam James | 2016-06-23
Schreibe einen Kommentar