Ionic 3 中的 CORS 地狱

我有一个 Ionic 应用程序与之通信的后端服务器(Spring Boot,由 nginx 代理).对于每个请求,它都会发送以下标头:access-control-request-headers: *, access-control-allow-headers: *, access-control-allow-origin: *, access-control-allow-methods: GET, POST, PUT, HEAD, OPTIONS, DELETE, PATCH.没有例外.

I have a backend server (Spring Boot, proxied by nginx) that my Ionic application communicates with. With every single request, it sends the following headers: access-control-request-headers: *, access-control-allow-headers: *, access-control-allow-origin: *, access-control-allow-methods: GET, POST, PUT, HEAD, OPTIONS, DELETE, PATCH. No exceptions.

它还允许 OPTIONS 请求并为每个请求返回 HTTP 200.

It also allows OPTIONS requests and returns HTTP 200 for every one of them.

现在,我有一个使用 @angular/common/http 的 ionic 应用程序.在浏览器中,一切正常,我可以优雅地发出 GETPOST 请求.

Now, I have an ionic app that uses @angular/common/http. In browser, everything works fine, I can make GET and POST requests gracefully.

但在模拟器中(当我使用 ionic cordova emulate ios 运行时,我只能发出 GET 请求,POST 失败并显示以下内容:

But in emulator (when I run with ionic cordova emulate ios, I can only make GET requests, POSTs fail with the following:

{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

如您所见,它显示 status: 0.这指的是 CORS 问题,但我不知道如何进一步调试.

As you can see, it says status: 0. This refers to a CORS issue, but I don't know how to further debug this.

我的请求都通过 Postman 成功,甚至使用 curl.只有在模拟器中才会失败.

My requests all succeed with Postman, and even with curl. It's only in emulator they fail.

推荐答案

CORS 再次,我希望这可能对某人有所帮助:

CORS again, I am hoping that this might help someone:

显然 Acccess-Control-Allow-Headers 标头的通配符 (*) 值仅在 2016 年 5 月被接受(reference1, reference2),所以一些浏览器可能仍然不支持它.所以,从:

Apparently wildcard(*) value for Acccess-Control-Allow-Headers header is only accepted in May 2016 (reference1, reference2), so some browsers might still not support it. So, changing from:

Access-Control-Allow-Headers: *

Access-Control-Allow-Headers: Content-Type, X-Auth-Token

(基本上,我的应用程序使用的标头的确切值),我能够解决这个问题.显然,我在桌面上使用的浏览器支持通配符标头值,但模拟器和设备的浏览器不支持.绝对不是设备与模拟器的问题,而是浏览器与浏览器的问题.

(basically, the exact value of headers my application uses), I was able to resolve the issue. Apparently browser I am using on my desktop supports the wildcard header value, but the browser of the emulator and device doesn't. Definitely not a device vs. emulator issue, but a browser vs. browser issue.

相关文章