问题
I'm having issue getting my ionic app to POST to my API. On my api I have set the following headers:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS");
When posting from Postman or the actual website, everything functions as expected and I see these headers come back but once I open up my app and send a request, it no longer works.
GET Requests are working fine, it's just POST requests that are broken. I use the following to send a post request on my app:
/**
* Post to the API
* @param path Where to go
* @param params What to send
*/
private post(path, params): Promise<any> {
return this.http
.post(this.apiUrl + path, params)
.toPromise()
.then(r => r.json());
}
I get the following error inside of my ionic app
Failed to load resource: Preflight response is not successful
XMLHttpRequest cannot load https://mmcalc.com/api/calculate. Preflight response is not successful
I've been pulling my hair out over this for nearly 15 hours now, I don't understand why it won't work.
回答1:
If you're only having the issue in iOS then it sounds like an issue with WKWebView
https://ionicframework.com/docs/wkwebview/
When the server receives the OPTIONS request, what does it respond with?
I would make sure the response from the OPTIONS request contains the headers WKWEBView is expecting, otherwise it will prevent the code from the making the call.
回答2:
The solution was very simple but not very obvious, I simply had to set the proper headers on my API. This article solved the issue for me and was very simple.
# Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
回答3:
the preflight request uses the OPTIONS request method. You should make sure that your API endpoint returns a successful status code for the OPTIONS request method and the response should also include the CORS headers which you have mentioned above. GET requests are probably working because they dont need a prefligh request. I would guess that in your case the OPTIONS method returns a wrong status code.
来源:https://stackoverflow.com/questions/50775046/preflight-response-is-not-successful-with-proper-headers