Setting up CORS to my Rails API

ADMAT Bandara
3 min readApr 4, 2019

We have started building our project’s front end with Angular 7. Sithum Meegahapola, Our Trainee Software Engineer is working on this task. He recently started to capture data from the API. API is handled by myself and it is a Rails API.

Today he executed his first API calling task with angular and ended up with the following issue.

CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

Solutions

Sithum Meegahapola already came up with a solution. That is to disable the security in the browser. ( Not a very convenient solution but Okay for the development)

Anyway, the best practice to do is to handle this the rails app level.

1. User rack-cors Gem

2. Bundle install

3. Add the configuration in the Application.rb

Origins can be specified as a string, a regular expression, or as ‘*’ to allow all origins.

A Resource path can be specified as exact string match (/path/to/file.txt) or with a '' wildcard (`/all/files/in/`).

Resource options

  • methods (string or array): The HTTP methods allowed for the resource.
  • headers (string or array or :any): The HTTP headers that will be allowed in the CORS resource request. Use :any to allow for any headers in the actual request.
  • expose (string or array): The HTTP headers in the resource response can can be exposed to the client.
  • credentials (boolean): Sets the Access-Control-Allow-Credentials response header.
  • max_age (number): Sets the Access-Control-Max-Age response header.
  • if (Proc): If the result of the proc is true, will process the request as a valid CORS request.
  • vary (string or array): A list of HTTP headers to add to the ‘Vary’ header

This will solve the problem of CORS.

Cheers, Happy coding !!!

References

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://www.rubydoc.info/gems/rack-cors/0.4.0

--

--