Creating API for Ionic app with Ruby On Rails. Part 1. CORS

Everybody, who started building a app using hybrid tools such Cordova or Ionic with custom HTTP API, usually gets the problem like

This happens because your app is actually running in browser and its built-in mechanisms prevents HTTP requests to other domains. But this can be easily solved with Ruby on Rails.

To enable CORS on your Rails app, you’ll need to add a few headers and process OPTIONS requests. Let’s take a look how to do this.

First of all, you’ll need the ApiController (app/controllers/api_controller.rb):

Than add the required routes to config/routes.rb:

That’s all! Now you’ll need to inherit your API controllers from the ApiController defined above and your new controller will automatically include the CORS support. Like this (app/controllers/api/orders_controller.rb)

Additional information about CORS can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *