VSCode调试控制台上出现“ Access-Control-Allow-Origin”错误,但在Chrome DevTools的“网络”标签上显示了200OK代码

时间:2019-05-07 19:23:34

标签: angular angular-httpclient

在使用HttpClient的Angular 7项目中,我在单击按钮处理程序上有以下简单的代码行:

    this.http
      .get('http://localhost:30123/api/identity/name/' + this.name)
      .subscribe((answer: Identity[]) => {
        this.identities = answer;  // debug does not get here...
      });

在VSCode的“控制台调试”选项卡上引发此错误:

Access to XMLHttpRequest at 'https://dihgldata.ingeniusds.cat/api/identitat/nom/montilla' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
[http://localhost:4200/] core.js:15724 {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://dihgldata.ingeniusds.cat/api/identitat/nom…", ok: false, …}

但是...

我正在使用三种不同的工具来测试相同的URL,并从api获得正确的响应。

第一名:邮递员。

(好吧,您知道:标头,CONTENT-TYPE,...在发送时是不同的     而不是chrome)

第二个:VS Code Extension Rest Client。

(根据Postman,这些实用程序对于测试API很有用,但对解决客户端代码中的错误没有帮助)

第三项:Chrome DevTools。

这是我的大事。我转到Chrome DevTools上的“网络”标签,可以在API被代码处理之前看到该API的响应,并且响应状态为OK-200。

在Chrome DevTools的“控制台”选项卡上没有错误。

使用带有Chrome Extension跟踪的VS Code集成调试器永远不会到达将答案分配给本地变量的行,并且错误在VSCode调试控制台中显示,没有其他提示。

编辑

尝试使用与Chrome地址栏上的Angular HttpClient相同的URL,并正确显示来自同一API的响应。

1 个答案:

答案 0 :(得分:1)

当您从其他任何网址向http://localhost:30123/请求时,它将被http://localhost:30123/的CORS(跨原始资源共享)政策阻止。

您必须允许来自任何URL或仅来自http://localhost:4200/的CORS。

在Java中,您可以使用CORS过滤器。 https://howtodoinjava.com/servlets/java-cors-filter-example/

相关问题