gpt4 book ai didi

java - 无法在 Spring Boot 数据休息中启用 CORS

转载 作者:行者123 更新时间:2023-11-30 02:51:00 25 4
gpt4 key购买 nike

我需要在 Spring Boot Data Rest api 中启用全局 CORS,以防止每当我从浏览器调用我的 api 时出现以下错误: http://localhost:8090/posts?user-id=1 。请求的资源上不存在“Access-Control-Allow-Origin” header 。来源'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'
}

最佳答案

因此,在评论中讨论我发现的内容后,您可以在 addCorsMappings 方法中尝试此操作

registry.addMapping("/**").allowedOrigins("http://localhost:8090")
.allowedMethods("PUT", "DELETE", "GET", "POST");

关于java - 无法在 Spring Boot 数据休息中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com