CORS Problem with Ionic App and server

For several weeks we at ZETDC have had sync issues between our app developed using Ionic and our server running on Apache. Some of the data was syncing but some wasn’t because our server hadn’t implemented HTTP method called OPTIONS.

Definition: OPTIONS HTTP Method

For a certain HTTP requests, the browser does a “preflight request” using an OPTIONS request. In which case, the browser first checks to see if the domain and the verb are supported, by checking for Access-Control-Allow-Origin and Access-Control-Allow-Methods.

Problem: Cross-Origin Resource Sharing (CORS)

What we didn’t realise was that for any API query on different origin than the server origin the browser agent makes OPTIONS HTTP request first before any POST, PUT, DELETE etc requests to make sure that the request is not of malicious intent.

Solution: ACCESS-CONTROL-* Headers

So in your .htaccess file you basically just need to set access control headers. Also make sure that response body is empty for OPTIONS HTTP verb.

.htaccess:

Header set Access-Control-Allow-Origin “*”
Header set Vary “*”
Header always set Access-Control-Allow-Credentials “true”
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, Accept-Encoding, X-XSRF-TOKEN”
Header always set Access-Control-Allow-Methods “POST, GET, DELETE, OPTIONS”

Conclusion

It’s not recommended to set the header Access-Control-Allow-Origin to “*” but rather set it to specific origin address you would like allow to access the API.

References

  1. https://www.html5rocks.com/en/tutorials/cors/
  2. https://stackoverflow.com/questions/13400594/understanding-xmlhttprequest-over-cors-responsetext/13400954#13400954
)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade