CORS Hell in Ionic 3

2019-07-11 05:13发布

问题:

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.

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

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

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}}

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

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

回答1:

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

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: *

to

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.