java - 使用 Spring Boot、Spring Security 和 React 时发生 CORS 错误

标签 java reactjs spring-boot spring-security cors

早上好。

过去两天我一直在解决这个问题,所以我决定发布一个有关它的问题。

基本上我有一个 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 之前,只需在我的后端 Controller 中使用 @CrossOrigin(origins = "*") 一切都可以完美运行,但现在我总是收到该错误,即使 URL 配置为不通过Spring Security登录进行保护。

与此同时,我从 Postman 发出任何请求(用于登录的 POST 或用于获取数据的 GET)都没有问题。

我尝试在互联网上寻找解决方案,但仍然没有找到。

如果您需要我展示部分代码,请询问。

提前致谢。

最佳答案

尝试使用全局 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

一起使用

关于java - 使用 Spring Boot、Spring Security 和 React 时发生 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71173132/

相关文章:

java - 使用spring boot时无法连接mysql

java - 使用 Elastic Search 6.2.3 在 AWS EC2 上运行 Spring Boot 2.0.3 应用程序

java - 如何在 ListView 的第一行添加新帖子?

java - 绘制透明路径

javascript - 位置 "/"的匹配叶路由没有元素

ios - XCode 错误 'YogaKit.modulemap' 未找到

java - 将对象添加到二叉搜索树

javascript - 如何在纵向和横向模式下将具有固定宽度的 parent 居中

spring - Kotlin Spring boot @ConfigurationProperties 用于列表

java - 在 JBoss 上启动 Spring webapp 的问题