spring-cors-允许所有

问题描述 投票:0回答:2

在我的Spring boot应用程序中,当前我有此类:

@SpringBootApplication
public class TestApplication {
   public static void main(String[] args) {
      SpringApplication.run(TestApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/user").allowedOrigins("http://localhost:3000");
         }
      };
   }
}

它只允许我从http://localhost:3000访问或写入,但是我希望所有对象都可以访问此rest方法,例如http://localhost:1000http://localhost:9999或任何站点。

我如何启用它?

spring spring-boot cors
2个回答
0
投票

如果为每个API创建两个API(控制器)(一个用于读取,另一个用于编写)会更好。对于写使用此:

registry.addMapping("/user").allowedOrigins("http://localhost:3000");
//This will allow only calls from 3000 port to write

供阅读使用:

registry.addMapping("/user").allowedOrigins("http://localhost");
//This will allow reading via all ports.

0
投票

registry.addMapping("/**").allowedOrigins("*");方法中使用corsConfigurer()允许所有类型的请求。

更新后的代码将如下所示:

@SpringBootApplication
public class TestApplication {
   public static void main(String[] args) {
      SpringApplication.run(TestApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
         }
      };
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.