从'http:// ...'访问'https:// ...'的XMLHttpRequest已被CORS策略阻止(Spring Boot&Angular 7)

问题描述 投票:0回答:3

我正在使用Spring Boot和Angular 7创建一个示例应用程序。在spring boot中,我将http转换为https。在角度应用程序中,客户端发布功能无法调用服务器Api post方法。

它抛出以下错误

从'https://localhost:8082/Demo/list'访问'http://localhost:4200'的XMLHttpRequest已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。

客户端角度7

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  firstClick() {
    return console.log('clicked');
  }
  getList() {
    return this.http.get('https://localhost:8082/Demo/list');
  }
}

客户端

  constructor(private data: DataService) {}

  ngOnInit() {
     this.data.getList().subscribe(data => {
       this.tempList = data
       console.log(this.tempList);
     });
  }

服务器

@CrossOrigin(origins = "http://localhost:4200")
@Controller
spring-boot http-post angular7 allow-same-origin
3个回答
1
投票

根据Spring Security,您应该启用localhost域以允许访问,或允许所有域访问(不安全)

https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

0
投票

您必须启用localhost域才能允许访问。然后创建它的bean。

public class CORSFilter extends GenericFilterBean implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Credentials", "*");
    httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    filterChain.doFilter(servletRequest, servletResponse);

}

}

@Bean
public FilterRegistrationBean filterRegistrationBean(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
    registrationBean.setName("CORS FIlter");
    registrationBean.addUrlPatterns("/*");
    registrationBean.setOrder(1);
    return registrationBean;
}

这适合我。谢谢。


0
投票

一个非常简单和优雅的解决方案是Spring 4.2.x CORS文档。

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

这是链接,https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html#_global_cors_configuration

虽然从Spring 5.1.x WebMvcConfigurerAdapter被弃用,所以应该使用WebMvcConfigurer

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.