Spring/Angular 启用 CORS 时出现 CORS 问题

Spring/Angular CORS issue while CORS is enabled

我正在使用 Spring 框架开发后端。我的前端是使用 Angular 框架编写的。我的 GET 请求被 CORS 策略阻止。

当我使用以下 angular 函数向 GET 资源发出请求时:

authenticate(credentials, callback) {

        const headers = new HttpHeaders(credentials ? {
            authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
        } : {});

        this.http.get("http://localhost:8080/user", {headers: headers}).subscribe(response => {
          console.log(response);
          console.log(this.authenticated);
            if (response['name']) {
                this.authenticated = true;
            } else {
                this.authenticated = false;
            }
            return callback && callback();
        });

    }

我在“网络”选项卡中收到失败的请求。根据我的安全配置,我有时也会收到 401,但在这两种情况下,我都会在控制台中收到“被 cors 阻止”消息。

这是请求发送到的控制器:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class AuthorizationController {

    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @RequestMapping("/user")
        public Principal user(Principal user) {

        System.out.println(user);
            return user;
        }

    }

这是我的 Spring 安全配置:

 @Override
    protected void configure(final HttpSecurity http) throws Exception {
              http.httpBasic()
                      .and().authorizeRequests().antMatchers("/**").permitAll()
                      .anyRequest().authenticated();

    }

注意:这不是我的首选配置。我正在使用它,因为它是我工作的唯一方法。使用此配置,我的 POST 请求可以正常工作。但是,我之前描述的 GET 请求不适用于此配置。

如有任何提示或帮助,我们将不胜感激,如果您需要有关我的代码的更多信息,请告诉我。

CORS 在浏览器中运行。对 Postman 做同样的操作,它应该会成功(如果 Java 代码正确)。

您是否设置了 angular 代理 和 运行?好像不是,因为你直接用域名

调用API

查看如何启用和使用代理 https://angular.io/guide/build#proxying-to-a-backend-server