[英]Jhipster CORS enable
我正在使用 Jhipster 生成 API。
我的 api 開啟了,我們稱之為:
我的 FE 應用程序正在運行:
這是我在 application-prod.yml 中啟用 Cors 的配置
cors:
allowed-origins: "https://staging.test.com/"
allowed-methods: "*"
allowed-headers: GET, PUT, POST, DELETE, OPTIONS
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
我仍然收到此錯誤:
對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。 因此不允許訪問源“ https://staging.test.com ”。 如果不透明響應滿足您的需求,請將請求的模式設置為“no-cors”以在禁用 CORS 的情況下獲取資源。
在 Spring boot 中還需要做些什么來啟用 CORS 嗎?
在 JHipster 的 Prod 模式下啟用 CORS 所需的唯一配置是設置jhipster.cors
配置,如下所示。 需要注意的一件事是,如果您的前端正在使用端口,則需要將其包含在allowed-origins
鍵中。
jhipster:
cors:
allowed-origins: "https://staging.test.com:8080"
allowed-methods: "*"
allowed-headers: "*"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
這由 JHipsterProperties 加載並在WebConfigurer.java 中用於應用 CORS 配置。
要在 PROD 模式下啟用 CORS, jhipster.cors
在基本application.yml
注釋掉jhipster.cors
並根據需要進行自定義。
cors:
allowed-origins: 'https://staging.test.com'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count,X-${jhipster.clientApp.name}-alert,X-${jhipster.clientApp.name}-error,X-${jhipster.clientApp.name}-params'
allow-credentials: true
max-age: 1800
如果您配置了任何新的根路徑,請確保它已在WebConfigurer.java
為 cors 注冊
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins())) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/newrootpath/**", config); // add this
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
source.registerCorsConfiguration("/v3/api-docs", config);
source.registerCorsConfiguration("/swagger-resources", config);
source.registerCorsConfiguration("/swagger-ui/**", config);
}
return new CorsFilter(source);
}
如果新的根路徑是使用另一個AuthenticationManager
(擴展WebSecurityConfigurerAdapter
的類)配置的,請確保CorsFilter
那里添加過濾器CorsFilter
。
面臨同樣的問題。 我發現的最簡單和最安全的方法是僅為您需要在控制器中公開的特定方法啟用 cors。 在為您的 api 提供服務的方法中,添加@CrossOrigin("*")
注釋。 這適用於生產,無需對 application-prod.yml 進行任何更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.