Setting up CORS to my Rails API
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.
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.
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
rack-cors | RubyGems.org | your community gem host
Middleware that will make Rack-based apps CORS compatible. Read more here…
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/`).
- 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
:anyto 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
- max_age (number): Sets the
- 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 !!!