我目前正在使用已經存在的 Spring Boot 后端開發 React 前端。
在本地開發時,我遇到了典型的 CORS 錯誤:
Access to fetch at 'http://localhost:8180/api/data/firms' from
origin 'https://localhost:8087' 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.
If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
runtime.js:98 GET http://localhost:8180/api/data/firms net::ERR_FAILED
我已經嘗試了這篇文章中提到的大多數解決方案,但沒有任何幫助。通過添加這些片段之一
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
或者創建一個 CorsFilter,CORS 錯誤消失了,但現在 API 總是回傳 HTTP 500 錯誤。
有誰知道我的問題的解決方案?
uj5u.com熱心網友回復:
您可以將它添加到您的控制器類中。
@CrossOrigin(origins = "${cross.origin}")
@RestController
應用程式屬性
cross.origin=https://localhost:8087
uj5u.com熱心網友回復:
我為 Spring Boot添加了新答案。
此外,如果您正在使用create-react-app,您將避免 CORS 問題來設定代理。(在這種情況下,不需要更改 Spring Boot 設定。)
package.json:
"proxy": "http://localhost:8180",
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360704.html
