Spring Die globale CORS-Konfiguration funktioniert nicht, aber die Konfiguration auf Controller-Ebene funktioniert
Ich versuche CORS global über @ zu konfigurierWebMvcConfigurerAdapter
unten gezeigt. Zum Testen erreiche ich meinen API-Endpunkt über eine kleine Knoten-App, die ich erstellt habe, um einen externen Service zu emulieren. Wenn ich diesen Ansatz versuche, enthält die Antwort nicht die richtigen Header und schlägt fehl, s 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);
}
}
Jedoch wenn ich das @ benut@CrossOrigin
Annotation wie so funktioniert es gut mit den richtigen Kopfzeilen zu reagieren.
@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 fehlt, damit die globale Konfiguration funktioniert? (Befolgen Sie die Anweisungen hier.https: //spring.io/blog/2015/06/08/cors-support-in-spring-framewor). Ich habe das Gefühl, dass ich etwas Einfaches vermisse, da das Beschriften des Controllers einwandfrei funktioniert.