首页 > 解决方案 > 如何在不使用 Spring Security 的情况下解决 CORS 问题

问题描述

我有这个WebMvcConfigurer在服务器上部署时工作得很好。但是,当我尝试从本地提供的 Angular 项目向服务器发送请求时,出现以下错误。

从源“http://localhost:4200”访问“https://sub.domain.com/api/staff/logout”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我的配置如下:

@Configuration
@EnableWebMvc
public class WebMvcConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedOrigins("*")
                        .allowedHeaders("*")
                        .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                        .allowCredentials(true).maxAge(3600);
            }

            /**
             * To add our interceptor into Spring configuration, we need to override
             * addInterceptors() method WebMvcConfig class that implements WebMvcConfigurer.
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new AppInterceptor());
            }
        };
    }
}

我提到了其他问题,我没有找到任何解决我问题的方法。提前致谢。

标签: javaspring-bootspring-mvcspring-security

解决方案


在您的 Angular 应用程序中,您可以添加一个proxy.config.json将在本地为您解决 CORS 问题的方法。此配置仅影响在本地提供应用程序时,因此在生产环境中不会发生任何变化。

{
    "/api/*": {
      "target": "http://localhost:8080",
      "secure": false,
      "logLevel": "debug",
      "changeOrigin": false
    }
}

另外,请参阅此答案:https ://stackoverflow.com/a/47537203/9698467和 Angular 文档:https ://angular.io/guide/build#proxying-to-a-backend-server

这个想法是,即使前端和后端都在 上提供服务localhost,也有一个为 Angular 应用程序提供服务的本地服务器和一个为您的后端提供服务的本地服务器。它们都在不同的端口上提供服务,这会导致跨域问题。通过使用代理,您可以有效地将 Angular 后端请求路由到localhost:8080,因此从 Angular 客户端的角度来看,一切似乎都在同一个来源。


推荐阅读