gpt4 book ai didi

java - 来自 Angular 应用程序的请求被 Spring 应用程序中的 CORS 策略阻止

转载 作者:行者123 更新时间:2023-12-02 10:02:37 25 4
gpt4 key购买 nike

我正在尝试将请求从 Angular 前端发送到 Spring 后端公开的 REST Controller 。REST Controller 具有 @CrossOrigin 注释。

我正在使用 HttpClient 从 Angular 应用程序发送请求。

请求:

  const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + basicAuthHeader,
})
};
return this.http.get(this.address + this.addressStorage.loginEndpoint + '/' + playerName, httpOptions);

结果:

Access to XMLHttpRequest at 'xxx' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

postman 发送的相同请求给出了正确的响应。

我的假设:

我已经使用 Chrome 开发工具检查了网络选项卡: screen of network tab

问题是由于发送 OPTIONS 请求而不是 GET 请求而导致的吗?CORS 只允许 GET 方法?

假设我的猜测是正确的,那么将此组件添加到 Spring Boot 应用程序可以解决我的问题吗?

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {


@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}

不幸的是,我目前无法更改后端实现,因此我无法自己找到它。

其他信息:

  registerPlayer(player: PlayerDTO): Observable<Object> {
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
};
return this.http.post(this.address + this.addressStorage.createUserEndpoint, player, httpOptions);
}

此请求发送到同一 Controller 但在不同端点上返回正确的响应。

最佳答案

我相信您的服务器发送 Access-Control-Allow-Credentials 意味着在 Angular 上您还需要通知您的服务使用 'Access-Control-Allow-Credentials': '正确'

更新

Credentialed requests and wildcards When responding to a credentialed request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard. Preflighted requests

关于java - 来自 Angular 应用程序的请求被 Spring 应用程序中的 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com