早上好。
在過去的兩天里,我一直在與這個問題作斗爭,所以我決定發布一個關于它的問題。
基本上我有一個 Spring Boot 專案,它通過 React JS 前端執行基本的 CRUD 操作。在我將 Spring Security 添加到專案之前,一切似乎都運行良好。從那時起,每當我從前端發出請求(使用 axios)時,我都會收到以下錯誤:
Access to XMLHttpRequest at 'http://localhost:8080/calciatore/list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在實作 Spring Security 之前,一切都在我的后端控制器中完美運行@CrossOrigin(origins = "*"),但現在即使 URL 配置為不受 Spring Security 通過登錄保護,我也總是會收到該錯誤。
同時,我從 Postman 發出任何請求(用于登錄的 POST 或用于獲取資料的 GET)都沒有問題。
我嘗試在互聯網上尋找解決方案,但仍然沒有找到。
如果您需要我顯示一部分代碼,請詢問。
提前致謝。
uj5u.com熱心網友回復:
嘗試使用如下代碼所示的全域 CORS 配置以允許所有端點使用 CORS。
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods(CorsConfiguration.ALL)
.allowedHeaders(CorsConfiguration.ALL)
.allowedOriginPatterns(CorsConfiguration.ALL);
}
};
}
}
由于 spring boot 2.4 你應該使用allowedOriginPatterns而不是allowedOrigins. 您也不能同時使用通配符“*”credentials : true
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429144.html
