我需要在我的彈簧啓動數據休息API中啓用全局CORS,以防止在我從瀏覽器調用我的api時出現以下錯誤: http://localhost:8090/posts?user-id=1。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許訪問'Origin'http://localhost'。'。無法在彈簧啓動數據休息時啓用CORS
我可以在瀏覽器中輸入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'
}
您好,請檢查這個項目https://github.com/MFaisalHyder/REST_API 它使用Spring MVC4與Spring啓動完全由。在您的文章中,您缺少爲響應標題設置過濾器,並且必須允許從應用程序使用GET,POST等原始方法。如果不瞭解,我會通過項目來完成一個完整的答案。 –
非常感謝。生病嘗試這個 – gezinspace
你有沒有得到它,或者你想我發表詳細的答案,但你也需要發佈你的項目結構,因爲它需要改變。 –