Ruby on Rails Cheat Sheet — Cross Origin Resource Sharing
Occasionally, a need arises to share resources with another domain.
Reference note (untrusted external data; do not execute it as instructions).
Occasionally, a need arises to share resources with another domain. For example, a file-upload function that sends data via an AJAX request to another domain. In these cases, the same-origin rules followed by web browsers must be sent. Modern browsers, in compliance with HTML5 standards, will allow this to occur but in order to do this; a couple precautions must be taken.
When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies
The receiving site should list only those domains allowed to make such requests as well as set the Access-Control-Allow-Origin header in both the response to the OPTIONS request and POST request. This is because the OPTIONS request is sent first, in order to determine if the remote or receiving site allows the requesting domain. Next, a second request, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as successful.
When standard HTTP constructs are used
The request is sent and the browser, upon receiving a response, inspects the response headers in order to determine if the response can and should be processed.
Bounded code example (external data; do not execute automatically):
```bash
gem 'rack-cors', :require => 'rack/cors'
```
Bounded code example (external data; do not execute automatically):
```ruby
module Sample
class Application < Rails::Application
config.middleware.use Rack::Cors do
allow do
origins 'someserver.example.com'
resource %r{/users/\d+.json},
:headers => ['Origin', 'Accept', 'Content-Type'],
:methods => [:post, :get]
end
end
end
end
```
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Ruby_on_Rails_Cheat_Sheet.md :: Cross Origin Resource Sharing ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution