ohler55/agoo

How to use Rack::Cors

Closed this issue · 9 comments

Hi,

I'm trying to setup CORS on an Agoo server using the rack-cors gem, but:

use Rack::Cors do
# ...

in config.ru complains that Rack::Cors is an uninitialized constant, and requiring rack-cors complains that it cannot be found, despite installing it.

Is there a specific way I need to attach Rack middleware to Agoo?

There isn't anything special needed. It sounds more like a gem issue though. Is rack-cors the correct require name?

Try require 'rack/cors'

Yea, that was the problem. I'm still having no joy here, editing the config.ru from one of the examples -but I'm aware there's a high chance this is just me and nothing Agoo specific:

# The Rack handler.
class FlyHandler
  def self.call(req)
    [ 200, { }, [ "flying fish" ] ]
  end
end
# ...
use Rack::Cors do
  allow do
    origins "*"
    resource "*", headers: :any, methods: %i[get post options head]
  end
end

run FlyHandler

And I'm starting with:

$ bundle exec rackup -s agoo -Ographql=/graphql

Can you see anything obvious? If not I'll just close this, thanks.

Alternatively, wondering if I could skip Rack::Cors and just add the headers myself to the routes, but not sure how I'd hook that into the Agoo::GraphQL stuff.

Agoo has APIs for adding headers. Check out the example/graphql/song.rb file. Search for CORS.

I swear I searched the whole repo, don't know how I missed that!

Sorry for bothering!

All good. It's nice to know people are using my software.

Hi @ohler55 ,

I know you allow headers in graphql:

Agoo::GraphQL.build_headers = proc{ |req|
  origin = req.headers['HTTP_ORIGIN'] || '*'
  {
    'Access-Control-Allow-Origin' => origin,
    'Access-Control-Allow-Headers' => '*',
    'Access-Control-Allow-Credentials' => true,
    'Access-Control-Max-Age' => 3600,
  }
}

but how to write like that without graphql in Agoo::Server? example:

Agoo::Server.build_headers = proc{ |req|
  origin = req.headers['HTTP_ORIGIN'] || '*'
  {
    'Access-Control-Allow-Origin' => origin,
    'Access-Control-Allow-Headers' => '*',
    'Access-Control-Allow-Credentials' => true,
    'Access-Control-Max-Age' => 3600,
  }
}

I'm on the road today. I can look at this tomorrow.