首页 > 解决方案 > Cross Origin 如何在 Spring Boot 和 Angular Cli 之间工作?

问题描述

我正在关注本教程Spring/Angular

当我运行我的应用程序时,我收到此错误:

从源“ http://localhost:4200 ”访问“ http://localhost:8080/api/employees ”处的 XMLHttpRequest已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头出现在请求的资源。

我对 Cross Origin 提出了不同的问题,但我不知道在哪里插入它以及在上面插入什么,因为在教程中从未显示或使用它。

标签: angularspringspring-boot

解决方案


import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CORSConfiguration  {

   @SuppressWarnings("deprecation")
    @Bean
        public WebMvcConfigurer corsConfigurer()
        {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
                }    
            };
        }
}

推荐阅读