Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't appear to properly respond to OPTIONS request #18

Closed
RyanMarcus opened this issue Mar 15, 2015 · 4 comments
Closed

Doesn't appear to properly respond to OPTIONS request #18

RyanMarcus opened this issue Mar 15, 2015 · 4 comments

Comments

@RyanMarcus
Copy link
Contributor

In order to get CORS requests working with AngularJS, I had to use sinatra/cross_origin and add some special code to handle HTTP OPTIONS requests:

options "*" do
  response.headers["Allow"] = "HEAD,GET,PUT,DELETE,OPTIONS"

  # Needed for AngularJS
  response.headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept"

  200
end

I'm not sure if this is an AngularJS specific issue or a problem in general, but it does appear that Firefox often sends an OPTIONS request before doing any kind of cross-origin request.

@whatyouhide
Copy link
Contributor

OPTIONS requests before CORS requests are actually part of the CORS specification. In particular, they're called preflight requests and all browser implementing CORS correctly issue them (not only Firefox).

sinatra/cross_origin doesn't support automatic handling of preflight requests AFAIK. The problem is pretty common to all CORS libraries written for router-based frameworks (like Sinatra): the Sinatra router matches the path and the request method, so if you do:

get "/cors" do
  cross_origin
  # ...
end

it's tricky to setup an OPTIONS route on /cors automatically. What you did is probably the best solution right now.

@RyanMarcus
Copy link
Contributor Author

Thanks for the fast response! I think I understand the problem now (or I at least understand it substantially better than I did before).

I added a brief note to the README about the workaround and made a pull request.

whatyouhide added a commit that referenced this issue Mar 18, 2015
Added workaround to the README for issue #18
@whatyouhide
Copy link
Contributor

Fixed by #19, thanks @RyanMarcus!

@andrhamm
Copy link

For the record, I think a better solution is to use Sinatra::MultiRoute like so:

require 'sinatra/multi_route'
require 'sinatra/cross_origin'

route :get, :options, '/my_route' do
  cross_origin allow_origin: 'http://example.com', allow_methods: [:get]

  # return if this is an OPTIONS request
  status 204 and return if request.request_method.to_s.match(/^options$/i)

  # actual GET request stuff here
  body 'hello world'
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants