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

CORS Preflight Error in browser but postman request works

我对 angular 的世界还很陌生,所以请原谅我的问题

我在尝试通过 angular app

休息 API 时遇到以下错误

Access to XMLHttpRequest at 'http://localhost:8080/bean/user' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我的 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,所以我也尝试了,但没有成功。这是进行调用的 angular 片段

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});
  }

如有任何帮助,我们将不胜感激!

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