我正在使用Spring Boot 2.0.2,我的项目中有spring-starter-web和spring-data-jpa,我暂时不使用Spring Security。 我创建了RestControllers并为其添加了@CrossOrigin批注,并尝试使用此代码为我的角度应用启用CORS
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")..allowedOrigins("*").allowedMethods("GET","POST","DELETE","PATCH","OPTIONS");
}
}
};
}
但是仍然从我的角度应用程序中收到CORS错误
答案 0 :(得分:0)
尝试类似这样的方法: 创建一个名为 CorsConfiguration 或任何名称
的新类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 CorsConfiguration implements WebMvcConfigurer {
private static final String HTTP_LOCALHOST_4200 = "http://localhost:4200";
private static final String GET = "GET";
private static final String POST = "POST";
private static final String PUT = "PUT";
private static final String DELETE = "DELETE";
private static final String HEAD = "HEAD";
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
HTTP_LOCALHOST_4200).allowedMethods(GET, POST, PUT, DELETE,
HEAD).allowCredentials(true);
}
}