无法在Spring引导数据休息时启用CORS

时间:2016-07-29 17:35:11

标签: java spring-mvc spring-boot cors spring-data-rest

我需要在我的spring boot数据rest api中启用全局CORS,以防止每次从浏览器调用我的api时出现以下错误: http://localhost:8090/posts?user-id=1。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost”访问。'。

我可以在浏览器中键入url并接收该资源的正确获取响应,但我无法通过网页中的ajax调用进行相同的调用。

我缺少什么想法?

我的代码和配置如下:

@SpringBootApplication
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableWebMvc
public class Application  {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);

}

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    };
}

@Bean
public CommandLineRunner demo(UserRepository userRepository, PostRepository postRepository,
                              CommentRepository commentRepository, EventRepository eventRepository, VenueRepository venueRepository) {
    return (args) -> {

        User user = new User("fsdsdfsd","sdsdsds","121212");
        userRepository.save(user);

        Venue venue = new Venue("dsaesrdfddgd","aerttyhyyty","yyyyyyyyyyyyyy");
        venueRepository.save(venue);

        Event event = new Event("dsaesrdfddgd","aerttyhyyty","yyyyyyyyyyyyyy",venue,user);
        eventRepository.save(event);

        Post post = new Post("some posts are funny. Some are not.",user, event);
        postRepository.save(post);

        Comment comment = new Comment("commmentntnrnejfnerfdgdfgdfdt", user, post);
        commentRepository.save(comment);
    };
}

}

@RepositoryRestResource
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {


Page<Post> readBydeletedIsFalseOrderByCreated(Pageable pageRequest);

@CrossOrigin
Post readByIdAndDeletedIsFalse(Long postId);

}

buildscript {
repositories {
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'project'
    version = '0.1.0'
}

war {
    baseName = 'project'
    version = '0.1.0'
}


repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-rest")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

3 个答案:

答案 0 :(得分:2)

因此,在我发现的评论中进行讨论后,您可以在 addCorsMappings 方法中尝试此方法

import atexit
import sys

def fatal_handler():
    try:
        e = sys.last_value
    except AttributeError: # no exception prior to execution of fatal_handler
        return

atexit.register(fatal_handler)

答案 1 :(得分:0)

添加这个bean有助于

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

有趣的是,spring并不允许使用后续bean在Spring引导数据休息端点上支持CORS。但是,它与开发人员创建的其他自定义端点一样有效。

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET");
        }
    };
}

答案 2 :(得分:-1)

尝试在全局配置中添加:

registry.addMapping("/**").allowedOrigins("*");