在我的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:1000
〜http://localhost:9999
或任何站点。
我如何启用它?
如果为每个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.
在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("*");
}
};
}
}