使用@CrossOrigin註解, 且要指定origins={"host1","host2"...}和allowCredentials = "true"
註解可以放在方法上或controller類上。
而不能直接使用@CrossOrigin,會報
Access to fetch at 'http://xxxx2' from origin 'http://xxxx1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
也不能設置origins="*", 因爲新版的瀏覽器已經不允許爲'Access-Control-Allow-Origin' *了;
也要設置allowCredentials = "true", 不然allowCredentials默認是空字符,瀏覽器也會報錯。
=========================================
官網上的全局設置方式已經失效了:https://spring.io/guides/gs/rest-service-cors/
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}