
一个简单的 Spring Boot Demo,使用了 Actuator,配置文件如下:
spring: security: user: name: xf password: 123456 management: server: port: 8090 servlet: context-path: /sys endpoint: health: show-details: always endpoints: web: exposure: include: '*' cors: allowed-origins: http://localhost:3000 allowed-methods: GET allowed-headers: '*' exposed-headers: 'Access-Control-Allow-Origin' allow-credentials: true 浏览器能正常访问http://localhost:8090/sys/actuator。
但是使用Postwoman调试的时候出现CORS问题:

使用火狐测试如下:

其实这个问题笔者之前遇到过,在方法上加上@CrossOrigin注解即可:
@CrossOrigin(origins = "http://localhost:3000") 但这个只是针对某个方法的,而且一般在 Controller 层加上,并且尝试过在启动类加上上面的注解无效。
另外去搜索过也添加了如下的配置:
@Configuration public class WebConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:4200"); } }; } } 也无效。
最后也尝试过修改配置文件:
management: server: port: 8090 servlet: context-path: /sys endpoint: health: show-details: always endpoints: web: exposure: include: '*' cors: allowed-origins: http://localhost:3000 allowed-methods: GET allowed-headers: '*' exposed-headers: 'Access-Control-Allow-Origin' allow-credentials: true 也无效。
因为笔者有使用浏览器代理扩展,但是关了代理也无效。
加入Basic Auth认证后,使用Postman测试一切正常:

去搜索过Spring Boot的文档,里面只是简单的提到配置文件的设置:

也就是上面 2.2 中的已尝试过的方法,另外也去搜索过Postwoman的Github Issue,里面是有提到CORS的问题,但是没有涉及到Spring Boot:

所以求助各位大神这个CORS问题应该怎么处理???
(真给跪了。。。。)
1 tcfenix 2020-09-01 17:27:43 +08:00 你配置的 allow origins 是 http://localhost:3000 那么你的请求的 header 带上 origin http://localhost:3000 了么? |
2 tcfenix 2020-09-01 17:30:23 +08:00 如果 spring boot 的代码没有写错的话,只要你的 header 里面带上 origin:http://localhost:3000 那么他就会在回包的时候把这些 Access-Control-Allow-Origin 还有 Methods Credentials Headers 啥的都带上 |
3 u6b7b5fc3 OP 补充一下,Postwoman 的请求 Header 也带上了 http://localhost:3000 了:  |
4 css3 2020-09-01 17:35:28 +08:00 跨域问题,前后端请求的域名不一致 |
5 css3 2020-09-01 17:36:09 +08:00 可以用 nginx 转发啊,前后端都转到 nginx 就是同域名了 |
6 u6b7b5fc3 OP 都没有部署啊,就本地测试的一个简单的 Spring Boot Actuator |
7 zhenjiachen 2020-09-02 20:48:05 +08:00 via iPhone 因为你集成了 security,需要配置一个 security 的配置,开放所有的 Actuator 接口就行 |
8 zhenjiachen 2020-09-02 20:49:35 +08:00 via iPhone |
9 u6b7b5fc3 OP @zhenjiachen 添加了 ActuatorSecurity 之后还是不行 |