我有一個 Angular 應用程式,它試圖通過 Spring Gateway 應用程式向微服務發送 GET 請求。
我已經在微服務 (helloworld) 上配置了允許來源以允許來自 localhost:4200。如果我將 angular 應用程式配置為使用 helloworld 直接 url,則請求將成功并得到我期望的回應。
我已經配置了我的 Spring Gateway 應用程式來提供和使用它自己作為中間人的 helloworld 應用程式對話的路徑。這通過瀏覽器作業,我得到了與以前相同的成功回應。
但是,當我將 Angular 應用程式配置為通過 Spring Gateway 應用程式時...當 Angular 應用程式嘗試通過 Spring Gateway 進行聯系時,我在瀏覽器中收到錯誤訊息:
CORS 策略已阻止來自 origin 的“http://localhost:4200”:對預檢請求的回應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。
所以它是拒絕請求的網關,它永遠不會到達 hello world 應用程式。這是網關應用程式的 yaml 配置:
server:
port: 8080
spring:
application:
name: gateway-service
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://localhost:4200"
allowedMethods:
- POST
- GET
- OPTIONS
allowCredentials: true
routes:
- id: hello
uri: lb://helloworld
predicates:
- Path=/hello/*
eureka:
client:
fetch-registry: true
register-with-eureka: false
service-url:
defaultZone: http://localhost:8761/eureka
這是我對網關服務的打字稿基本呼叫:
this.httpClient.get<string>('http://localhost:8080/hello/hi')
.subscribe((response) => {
console.log(response);
}, error => {
console.log(error);
});
正如您所看到的,我使用 eureka 來決議應用程式,但這在瀏覽器中進行了測驗。任何幫助將非常感激。
===EDIT=== 以下配置確保沒有 Spring 安全依賴解決了這個問題:
spring:
application:
name: gateway-service
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://localhost:4200"
allowedMethods:
- POST
- GET
- OPTIONS
allowedHeaders: "*"
allowCredentials: true
routes:
# - id: auth
# uri: lb://java-api-workflow-auth
# predicates:
# - Path=/java-api-workflow-auth/*
- id: hello
uri: lb://helloworld
predicates:
- Path=/hello/*
uj5u.com熱心網友回復:
您的 CORS 配置至少存在兩個問題。
localhost:4200 不是起源
該http://部分在開始時丟失。試試吧allowedOrigins: "http://localhost:4200"。看
- MDN 網路檔案詞匯表:起源
- 這是對類似問題的回答。
不允許有憑據的請求通配符
如果您允許憑據,則不能使用通配符 ( *) 來允許方法、標頭和/或來源;相反,您必須明確列出允許的值。有關 CORS的MDN Web Docs上有關此例外的更多詳細資訊。
uj5u.com熱心網友回復:
下面的配置確保沒有 Spring 安全依賴解決了這個問題:
spring:
application:
name: gateway-service
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://localhost:4200"
allowedMethods:
- POST
- GET
- OPTIONS
allowedHeaders: "*"
allowCredentials: true
routes:
# - id: auth
# uri: lb://java-api-workflow-auth
# predicates:
# - Path=/java-api-workflow-auth/*
- id: hello
uri: lb://helloworld
predicates:
- Path=/hello/*
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385195.html
