【发布时间】:2016-12-04 12:09:54
【问题描述】:
我需要在我的 spring boot data rest api 中启用全局 CORS,以防止每当我从浏览器调用我的 api 时出现以下错误: http://localhost:8090/posts?user-id=1。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,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'
}
【问题讨论】:
-
您好,请检查这个项目github.com/MFaisalHyder/REST_API 它完全是使用带有 Spring Boot 的 Spring MVC4 制作的。在您的帖子中,您缺少为响应标头设置过滤器,并且还必须允许从应用程序使用 GET、POST 等原始方法。如果不理解,请通过项目,我将在完整的答案中描述。
-
非常感谢。我试试这个
-
您收到了吗,或者您希望我发布详细的答案,但您也需要发布您的项目结构,因为它需要更改。
-
嗯,老实说,我很挣扎,虽然这篇文章看起来真的是我想要的。如果您能帮助我提供更详细的答案,我将不胜感激。至于项目结构....我目前将所有内容都保存在一个名为 hello 的包中——这不是一件好事,但我的项目已经被缩减了,所以我可以先让简单的事情开始工作——所以现在还可以
-
问题是,如果你在 GOD 课程中工作,事情就不会是模块化的。 spring.io/guides/gs/rest-service 按照他们的指南设置您的项目。!
标签: java spring-mvc spring-boot cors spring-data-rest