-1

当我尝试通过在 Angular 6 中使用 HttpClient 对后端 API 执行 POST 操作时出现此错误。我收到此错误:“CORS 标头 'Access-Control-Allow-Origin' 缺失”。

我的临时解决方案是在 Google Chrome 浏览器上安装 CORS 扩展。

解决此问题的最佳解决方案是什么?

谢谢你。

4

1 回答 1

0

您需要启用后端服务以接受来自 Angular 6 网站的请求。这个东西叫做CORS(跨域资源共享)。默认情况下,您的网站网址是http://localhost:4200

执行此操作的方法取决于您用于开发后端服务的语言/框架。

这是 SpringBoot 中配置 CORS 的示例。它仅用于开发目的,您应该至少限制访问,将通配符转换为您需要的数据(例如您的 url,如前所述)。

@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }




@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // we don't need CSRF because our token is invulnerable
                .csrf().disable()

                // TODO adjust CORS management
                .cors().and()

                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

                // don't create session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .authorizeRequests()

                .antMatchers("/auth/**").permitAll()
                .anyRequest().authenticated();

        // Custom JWT based security filter
        JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
        httpSecurity
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
于 2018-07-18T13:22:32.487 回答