【问题标题】:CORS Preflight Error in browser but postman request works浏览器中的 CORS 预检错误,但邮递员请求有效
【发布时间】:2021-08-23 13:57:04
【问题描述】:

我对 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,所以我也尝试了,但没有成功。这是一个可以调用的角度 sn-p

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

任何帮助将不胜感激!

【问题讨论】:

  • 从您问题的标题看来,您似乎对邮递员的工作感到惊讶。浏览器执行跨域检查,而 Postman 不执行。这就是为什么。
  • 您的 Spring 应用程序必须将标头发送回您的 Web 应用程序,告诉它允许跨源请求。例如,它来自的域。

标签: java angular spring-boot spring-security


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2018-03-29
    • 1970-01-01
    • 2021-06-09
    • 2013-06-25
    • 1970-01-01
    • 2016-12-11
    • 2020-05-18
    相关资源
    最近更新 更多