【问题标题】:CORS header ‘Access-Control-Allow-Origin’ missing. When post to API缺少 CORS 标头“Access-Control-Allow-Origin”。发布到 API 时
【发布时间】:2018-07-18 12:59:20
【问题描述】:

当我尝试在 Angular 6 中使用 HttpClient 对后端 API 执行 POST 操作时收到此错误。我收到此错误:“CORS header ‘Access-Control-Allow-Origin’ missing”。

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

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

谢谢。

【问题讨论】:

    标签: typescript httpclient angular6


    【解决方案1】:

    您需要启用后端服务以接受来自 Angular 6 网站的请求。这个东西叫做CORS (Cross-origin resource sharing)。默认情况下,您的网站网址是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);
        }
    

    【讨论】:

    • 感谢您提供的信息。后端服务建立在JAVA平台之上。
    猜你喜欢
    • 1970-01-01
    • 2018-03-28
    • 2019-02-07
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2021-12-07
    相关资源
    最近更新 更多