浏览器中的 CORS 预检错误,但邮递员请求有效

时间:2021-06-06 02:43:39

标签: java angular spring-boot spring-security

我对 Angular 的世界还很陌生,如果这是一个愚蠢的问题,请原谅

当我尝试通过 angular 应用程序点击 rest API 时出现以下错误

<块引用>

从“http://localhost:8080/bean/user”访问 XMLHttpRequest 来源 'http://localhost:4200' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

这是我的 spring 安全配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
        .csrf().disable()   
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
        .httpBasic();   
    }

我尝试向 API 添加跨域注释,但它也不起作用

@CrossOrigin(origins="http://localhost:4200")
@GetMapping(path="/bean/{name}")
public Bean path(@PathVariable String name) {
    return new Bean(name);
}

有人建议将内容类型设为 text/plain,所以我也尝试过,但没有成功。这是一个调用的角度片段

executeBeanService(name: string) {
    let basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();
    let header = new HttpHeaders ( {
      'Content-Type':'text/plain',
      Authorization: basicAuthHeaderString

    })

    return this.http.get<Bean>(`http://localhost:8080/bean/${name}`,
    {headers: header});
  }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

错误现已解决。问题是组件扫描。由于这是 Spring Boot 应用程序,因此安全配置应该在与声明 @SpringBootApplication 注释的类相同的包/子包中。就我而言,包的名称不同。重构包名称并重新启动应用程序解决了问题。