Issue
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.
Solution
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]
Answered By - Joe Scotto
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.