我有三个带有 Micronaut 的微服务和一个带有 Spring Boot 的 Spring Cloud Gateway:
我已经使用下面的 YAML 配置了网关:
spring:
application:
name: spring-api-gateway
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
- HEAD
- PATCH
- TRACE
routes:
- id: course-service
uri:
${COURSE_SERVICE_URL:http://localhost:8081}
predicates:
- Path=/course/**, /swagger/**
- id: assessment-service-get
uri: ${ASSESSMENT_BFF_SERVICE_URL:http://localhost:8083}
predicates:
- Path=/assessment/**
- Method=GET
filters:
- RewritePath=/assessment/, /bff/assessment/
每个微服务都启用了CORS配置,如下
micronaut.server.cors=true
没有RewritePath我就没有脸CORS。然而,当使用 RewritePath 时,请保持从前端面向 CORS
Access to XMLHttpRequest at 'http://localhost:8080/assessment' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
对我来说问题是我在方法上缺少选项
spring:
application:
name: spring-api-gateway
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "http://localhost:4200"
allowedHeaders: "*"
allowedMethods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
- HEAD
- PATCH
routes:
- id: course-service
uri:
${COURSE_SERVICE_URL:http://localhost:8081}
predicates:
- Path=/course/**, /swagger/**
- id: assessment-service-get
uri:
${COURSE_SERVICE_URL:http://localhost:8083}
predicates:
- Path=/assessment/**
- Method=GET,OPTIONS <-- adding OPTIONS resolve the issue
filters:
- RewritePath=/assessment/?(?<segment>.*), /bff/assessment/$\{segment}
- id: assessment-service-post-put-delete
uri:
${COURSE_SERVICE_URL:http://localhost:8082}
predicates:
- Path=/assessment/**
- Method=POST,PUT,DELETE,OPTIONS <-- adding OPTIONS resolve the issue