gpt4 book ai didi

java - 请求中不存在 'Access-Control-Allow-Origin' header

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

我已经阅读了很多有关此的主题,但它仍然不起作用,我失去了理智。

我有一个 Angular6 应用程序,带有 Spring Api,当我调用它时,我一直遇到此错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

但我觉得我做了一切:

这是我在 Angular 应用程序中对 api 的调用:

getGamesFromServer() {
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*'
})
};

this.httpClient
.get<any[]>('http://localhost:8080/api/rest/v1/game/progress', httpOptions)
.subscribe(
(response) => {
console.log(response);
this.games = response;
console.log(this.games);
this.emitGameSubject();
},
(error) => {
console.log('Erreur ! : ' + error);
}
);
}

这里是调用的java方法:

@RequestMapping(method = GET, value = "/progress")
@ResponseBody
public Response findAllAndProgress() {
return Response.status(Response.Status.OK)
.entity(gameService.findAllAndProgress())
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.build();
}

我还启动了 chrome,并激活了 --disable-web-security 选项,并且我还下载了一个 chrome 扩展以允许 CORS 请求,但没有用

最佳答案

我假设这是因为 Angular 应用程序在开发模式下运行,并且从与 Spring Web 应用程序不同的端口提供服务。您可以使用为应用启动指定的 proxy.conf.json 文件 (ngserve --proxy-config proxy.conf.json) 或作为解决此问题一个快速但肮脏(但不太适合生产)的解决方案,您可以将 @CrossOrigin(origins = "*") 添加到您的 Spring Controller 。

以下代码不起作用的原因:

@RequestMapping(method = GET, value = "/progress")
@ResponseBody
public Response findAllAndProgress() {
return Response.status(Response.Status.OK)
.entity(gameService.findAllAndProgress())
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.build();
}

是因为该方法从未真正执行来添加 header 。跨源请求在发出实际请求(在您的情况下为 HTTP GET)之前启动预检请求(HTTP OPTION)。正是该预检请求失败了。这就是为什么向 Controller 添加注释可以解决该问题的原因。

关于java - 请求中不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52627884/

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