Giter Site home page Giter Site logo

Comments (90)

yonkeltron avatar yonkeltron commented on July 3, 2024 6

+1 from me.

Using rack-cors as per the readme in a rails-api project and I see no headers added by the gem if I do a GET. If I do a POST, I can get the headers properly when I tested using the Chrome Postman app.

Code for middleware insertion (copied verbatim from README):

    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

All headers returned:

Access-Control-Allow-Credentials →true
Access-Control-Allow-Methods →GET, POST, OPTIONS
Access-Control-Allow-Origin →chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Access-Control-Max-Age →1728000
Cache-Control →max-age=0, private, must-revalidate
Content-Type →text/html
ETag →"7215ee9c7d9dc229d2921a40e899ec5f"
Transfer-Encoding →chunked
Vary →Origin
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-Request-Id →72f58d72-e89c-48a4-a80e-1f8f52c2b5fe
X-Runtime →0.017717
X-UA-Compatible →chrome=1
X-XSS-Protection →1; mode=block

Environment information:

ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]

Rails 4.0.0

Darwin A-strong-preference-for-raincoats.local 12.5.0 Darwin Kernel Version 12.5.0: Sun Sep 29 13:33:47 PDT 2013; root:xnu-2050.48.12~1/RELEASE_X86_64 x86_64

Please let me know if I can provide any additional information. Thanks!

from rack-cors.

zigomir avatar zigomir commented on July 3, 2024 3

I have same problem, but only when running in production mode. For development it works OK. I'm using vanilla Rails 4.

Edit:
Ah, I needed to use config.middleware.insert_before ActionDispatch::Static, Rack::Cors do and this to work you need to set config.serve_static_assets = true in production.rb.

from rack-cors.

flauwekeul avatar flauwekeul commented on July 3, 2024 3

So, to summarize: currently the only way to fix this is to use config.middleware.insert_before ActionDispatch::Static, Rack::Cors do and enable config.serve_static_assets in production.rb?

It works, but I really don't want to enable static assets 😞

from rack-cors.

dcunited001 avatar dcunited001 commented on July 3, 2024 2

I donno, it's working for me on Heroku with Rails 4.2.0.beta2, when I configure CORS in a Rackup file, as below.

  • However, this app is API only and not serving any static assets.
  • Also, I'm using the Devise Token Auth gem.
# This file is used by Rack-based servers to start the application.

require ::File.expand_path('../config/environment',  __FILE__)
run Rails.application

cors_origins = ENV.fetch('RAILS42_CORS_ORIGINS', '*')

require 'rack/cors'
use Rack::Cors do
  # TODO: secure
  allow do
    origins cors_origins
    resource '*',
             :headers => :any,
             :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
             :methods => [:get, :post, :options, :delete, :put]
  end
end

from rack-cors.

Bockit avatar Bockit commented on July 3, 2024 2

I ran into this problem, turned out it was because I was testing my api with cURL or by hitting the api directly in chrome. In both cases there is no Origin header on the request. Adding the Origin header to my request triggered the response headers to include Access-Control-Allow-Origin: http://127.0.0.1:4200 and etc.

curl -I --header "Origin: http://127.0.0.1:4200" http://localhost:3000/your/path/here

from rack-cors.

a0x avatar a0x commented on July 3, 2024 2

I think I met this problem in Rails 5.

Versions:

  • Ruby 2.6.1
  • Rails 5.2.2
  • rack-cors 1.0.2

Server is running under development env.

Results come first, as shown in the picture, I tried two requests with different origins, and the server gave me almost the same response(only with little difference in the headers).
image

Server SHOULD give 401, right?

Here's my config:

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'foobar.com'

    resource '*',
             headers: :any,
             methods: %i[get post put patch delete options head]
  end
end

Here're middlewares:

 $ rails middleware
use Rack::Cors
use Raven::Rack
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Bullet::Rack
run Hermes::Application.routes

from rack-cors.

jbutz avatar jbutz commented on July 3, 2024 1

@zigomir's solution works for me, though I tweaked it and I am using
config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do
so that I can get log messages. Has anyone managed to get this working on Heroku?

from rack-cors.

cyu avatar cyu commented on July 3, 2024 1

@thebravoman glad that was it.

Looking at the spec, it looks like the Origin header format is <scheme> "://" <hostname> [ ":" <port> ]. Maybe I should automatically strip out any starting slash by default.

from rack-cors.

jhdavids8 avatar jhdavids8 commented on July 3, 2024

Thanks @zigomir, that did it for me in Rails 4!

from rack-cors.

limitingfactor avatar limitingfactor commented on July 3, 2024

Master works for me

from rack-cors.

mgodwin avatar mgodwin commented on July 3, 2024

I have had it working off and on, but I can't seem to isolate what causes it to fail and succeed.

from rack-cors.

sulphur avatar sulphur commented on July 3, 2024

i use the same solution as @jbutz too and seems to work for me too

from rack-cors.

scottillogical avatar scottillogical commented on July 3, 2024

Should we change the README to insert_after ?

from rack-cors.

 avatar commented on July 3, 2024

Using config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger with rails-api does not appear to work for me for GET requests.

from rack-cors.

jtomaszewski avatar jtomaszewski commented on July 3, 2024

It should be definitely set in README - I searched the whole internet until I found a fix for that ..

from rack-cors.

 avatar commented on July 3, 2024

Thanks @zigomir that did it for me as well, although without static assets (since we're not serving them from Rails).

from rack-cors.

gabriel403 avatar gabriel403 commented on July 3, 2024

This worked for me thanks, was driving me mental

from rack-cors.

germs12 avatar germs12 commented on July 3, 2024

I used config.middleware.insert_before ActionDispatch::Static, Rack::Cors do and it worked. Thanks @zigomir

from rack-cors.

cyu avatar cyu commented on July 3, 2024

You shouldn't need to set config.serve_static_assets unless you need the CORS headers for static assets.

from rack-cors.

germs12 avatar germs12 commented on July 3, 2024

@cyu Any idea why this isn't working in rails 4? The "solution" stopped working for me recently (as well as others too from what I can see on the interwebs).

from rack-cors.

cyu avatar cyu commented on July 3, 2024

I create an example in examples/rails4 and it seems to work. Granted it's a very simple example, so if you can give me some more details I can try to reproduce the issue.

from rack-cors.

visoft avatar visoft commented on July 3, 2024

I copied the code verbatim from your application.rb file, yet I can't get it to work in my application. I still get "No 'Access-Control-Allow-Origin' header is present on the requested resource" from my client. Using Rails 4.2.beta1 and rails-api.

from rack-cors.

simondelorean avatar simondelorean commented on July 3, 2024

@visoft Did you manage to solve this issue? I'm using standard Rails 4.1.2, but can't get it to work either.

from rack-cors.

visoft avatar visoft commented on July 3, 2024

@simonbogarde, I haven't. I hacked my ApplicationController to do the CORs stuff using this approach. I really would like to use rack-cors instead.

from rack-cors.

simondelorean avatar simondelorean commented on July 3, 2024

@visoft Thanks. When I manage to fix this, I'll post the solution here.

from rack-cors.

jessesanford avatar jessesanford commented on July 3, 2024

I am also now having the same "No 'Access-Control-Allow-Origin' header is present on the requested resource" issue with rails 4.1.5 when using

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do

and also

config.middleware.insert_before "ActionDispatch::Static", "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do

from rack-cors.

dcunited001 avatar dcunited001 commented on July 3, 2024

i had this working on heroku about a year ago, then several months later, it stopped working, but only on heroku. before, it seemed to process my rackup file, but now it's not. just now looking into it.

from rack-cors.

a2f0 avatar a2f0 commented on July 3, 2024

I have the same issue on Rails 4.0.8, no additional headers being supplied in HTTP get requests after following the installation instructions.

from rack-cors.

Think4866 avatar Think4866 commented on July 3, 2024

I'm chiming in to say that I also have this issue after following the install instructions. I've also tried adding @dcunited001's code snippet to my config.ru as well.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

Anyone who's still having issues please post your middleware config and also the output of rake middleware. Also, please confirm that you are using the rails-api gem.

I have a feeling there might be different issues at play here. I might close this issue so I can better diagnose everyone's issues individually.

from rack-cors.

germs12 avatar germs12 commented on July 3, 2024

I am still having the issue. I've used before filters to set headers from within my controllers instead of this gem (unfortunately). I am not using the rails-api, but instead a full Rails 4.0.5 app.

from rack-cors.

a2f0 avatar a2f0 commented on July 3, 2024

This might have been a user education issue for me. The CORS specification is a little bit over my head; it seems that an Origin header is provided if I use an AJAX XMLHttpRequest(). I am still trying to make a determination of whether or not it is possible to do a CORS preflight check and GET request for assets that are served up via the asset pipeline (and expect an Origin header in this request). I have a post describing what I am trying to do here.

http://stackoverflow.com/questions/26303655/cross-domain-svg-content-document-in-object-tag/26305983#26305983

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@dsulli99 the answer to your solution depends your server infrastructure. I imagine in development rack-cors will work for you, but it won't in production. Most Rails containers will server assets directly instead of going through the Rails stack. I think in your case the the best thing to do is to write the necessary web server specific directives so that Access-Control-Allow-Origin: * is always returned for your SVG content.

from rack-cors.

pzagor2 avatar pzagor2 commented on July 3, 2024

I'm still having issues with this.
I'm running ruby 2.0.0 on Rails 4.1.5 without rails-api gem on Heroku. I'm not using this to serve static assets, but for making POST request with AJAX.

I have setup rack-cors in application.rb with

config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
...

When I'm in development everything works as expected. These are the headers returned by the server.
Gist copy of headers

But when I test in production (Heroku), with chrome I get. (Firefox throwing similar error)

XMLHttpRequest cannot load ******. The request was redirected to '****', which is disallowed for cross-origin requests that require preflight.

But if I test with Chrome App Postman, I get these headers back.
Gist copy of headers

So it does include proper Access-Control-Allow-Origin header, right?

I also tried putting rack-cors configuration in config.ru file, same results...

from rack-cors.

cyu avatar cyu commented on July 3, 2024

The redirect message is weird, any idea what's causing that? What's it redirecting to? Off the top of my head, it could be two things: 1) something upstream of Rack::Cors is causing a redirect which XHR doesn't like, or 2) Rack::Cors is passing the request through to the Rails app, which is responding with a redirect. It will do this if the Origin and path didn't match a configured resource in Rack::Cors. Can I see the Rack::Cors configuration and the URL that you're trying to hit?

from rack-cors.

pzagor2 avatar pzagor2 commented on July 3, 2024

I edited my post... because it's content was not retailed to solution.
@cyu was right. The problem was that I was making AJAX request to exapmle.com domain witch get redirected to www.example.com. And redirects are not allowed with CORS policy.
So I just chaned my AJAX request to include www in it's URL.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@pzagor2 are you running force SSL? That might be causing the redirect that the browser is complaining about.

from rack-cors.

coderberry avatar coderberry commented on July 3, 2024

I am running into this issue on development but only when I am forcing SSL using thin. Does this not work when using ssl?

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@cavneb Are you making the CORS request using https? Are you seeing any errors in the Chrome Inspector?

from rack-cors.

waiting-for-dev avatar waiting-for-dev commented on July 3, 2024

With the insert_after in Rails 4.1.6 and rails-api 0.3.0 worked for me, with POST and GET requests.

Thanks!

from rack-cors.

birarda avatar birarda commented on July 3, 2024

In Rails 4.1.6 with insert_before "Rack::Runtime", "Rack::Cors" rack-cors is not working for get requests for me. Works for PUT, OPTIONS.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@birarda can you paste here the output of rake middleware?

from rack-cors.

birarda avatar birarda commented on July 3, 2024
± rake middleware
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
use Rack::Cors
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x0000010989aeb8>
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
use Remotipart::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
use Rack::LiveReload
use Rack::Pjax
run DataWeb::Application.routes

So I'm guessing I need before ActionDispatch::Static in dev and before Rack::Runtime in production?

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@birarda yeah, you can do that - that was my initial thinking. It looks pretty gross to me though. I'm going to change the examples to insert before Rack::Sendfile, which in both environments will put it at the top of the Rack stack.

See #61

from rack-cors.

scervera avatar scervera commented on July 3, 2024

I am experiencing this problem too. I'm using Angularjs as a front end to add a record to my Rails application. Chrome was showing this error:
XMLHttpRequest cannot load http://localhost:3000/passages. The request was redirected to 'http://localhost:3000/passages/67', which is disallowed for cross-origin requests that require preflight.

I think I figured out why this is occurring. Here is my "create" action in the controller:

def create
    @passage = Passage.new(passage_params)
    respond_to do |format|
      if @passage.save
        format.html { redirect_to @passage, notice: 'Passage was successfully created.' }
        format.json { render :show, status: :created, location: @passage }
      else
        format.html { render :new }
        format.json { render json: @passage.errors, status: :unprocessable_entity }
      end
    end
  end

Note that once the passage is saved, I get redirected to the "show" action of the specific passage record created. Apparently, it is this redirection that is triggering the XHR error. However, I'm not sure how to configure the response so that this error is avoided. But that is a question for another forum. I hope this helps others too.

UPDATE: Posted my question to stackoverflow
https://stackoverflow.com/questions/26977623/rack-cors-error-on-redirection

from rack-cors.

cyu avatar cyu commented on July 3, 2024

Good catch - I think this behavior is caused by this in the spec:

cross-origin resource sharing 2014-11-17 12-23-55

So this is an issue with the spec and browsers and now with Rack::Cors. I can log a warning about this just so others don't get tripped up about this.

from rack-cors.

birarda avatar birarda commented on July 3, 2024

@cyu

switched to use Rack::Sendfile instead.

Now my rake middleware gives

[127] ± rake middleware                                                                                                                                                                                           ✘
use Rack::Cors
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000101d867b8>
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
use Remotipart::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
use Rack::LiveReload
use Rack::Pjax
run DataWeb::Application.routes

But rack-cors still isn't giving me any headers on GET. I have added :get to my methods in application.rb

from rack-cors.

cyu avatar cyu commented on July 3, 2024

Did you check and make sure you browser is passing an Origin header?

from rack-cors.

afeld avatar afeld commented on July 3, 2024

I got it working: 18F/C2#105. FYI, the README says "rails 3 example" twice, but the latter links to one in Rails 4.

from rack-cors.

aarongray avatar aarongray commented on July 3, 2024

I seem to be having this same problem. I am using the rails-api gem. None of the custom headers that I want to expose are appearing.

Here is my config code in config/environments/development.rb:

  config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> {Rails.logger }) do
    allow do
      origins 'localhost:4000'

      resource '*',
        :headers => :any,
        :methods => [:get, :post, :delete, :put, :options, :head],
        :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
        :max_age => 0
    end
  end

Here are the response headers in the browser:
image

And here is the output from rake middleware:

use Rack::Cors
use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007fcc462fb448>
use Rack::Runtime
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::ParamsParser
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
run Testapp::Application.routes

Any ideas?

from rack-cors.

kroofy avatar kroofy commented on July 3, 2024

@aarongray I had to make sure to add the :patch verb as well to make it work.

  config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> {Rails.logger }) do
    allow do
      origins 'localhost:4000'

      resource '*',
        :headers => :any,
        :methods => [:get, :post, :delete, :put, :options, :head, :patch],
        :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
        :max_age => 0
    end
  end

from rack-cors.

aarongray avatar aarongray commented on July 3, 2024

@kroofy Nice! Thanks for the pro tip.

from rack-cors.

wootaw avatar wootaw commented on July 3, 2024

I having this same problem. When in "rails s -e production", it is OK. But I use nginx/unicorn, it can not work.

config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
  allow do
    origins '*'
    resource '*', 
      :headers => ["Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"], 
      :methods => [:get, :post, :delete, :put, :patch, :options]
  end
end

from rack-cors.

pcasa avatar pcasa commented on July 3, 2024

Any update on this? Have same setup nginx/unicorn and still get Origin errors.

from rack-cors.

masonforest avatar masonforest commented on July 3, 2024

If you're hosting in Heroku you may need to move the configuration from application.rb to config.ru

http://stackoverflow.com/a/20465250

from rack-cors.

ethanator avatar ethanator commented on July 3, 2024

Try this Chrome extension if you're using Chrome. This is kinda cheating but may save your life! I only used it for testing and I'm not using it otherwise.

from rack-cors.

fuggfuggfugg avatar fuggfuggfugg commented on July 3, 2024

I cloned the Rails4 example as is > Added an image in the assets > bundle install > rails s.

Running Rails 4.1.5. I get a preflight-hit;no-origin. Any help is appreciated.

screen shot 2016-09-13 at 11 08 14 am
.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

no-origin means that no Origin header was provided with the HTTP request. That's what triggers a CORS exchange.

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

I'm having this issue as well. The weird part is that using postman my api calls work. My middleware is:

use Rack::Cors
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x000000017d1da0>
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use RequestStore::Middleware
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
run Moria::Application.routes

config/application.rb contains:

    config.middleware.insert_before 0, "Rack::Cors", :logger => (-> { Rails.logger }) do
      allow do
        origins '*'
        resource 'api/partner.json', headers: :any, methods: [:get]
        resource 'v2/api/partner.json', headers: :any, methods: [:get]
        resource 'v2/api/event.json', headers: :any, methods: [:get]
        resource 'v2/api/company.json', headers: :any, methods: [:get]
      end
    end

Whenever I make this call through a JS app I get:
No 'Access-Control-Allow-Origin' header is present on the requested origin. Origin 'http://localhost:8080' is there not allowed access.

production.log file shows:

DEBUG -- : Incoming Headers:
  Origin: http://localhost:8100
  Access-Control-Request-Method: 
  Access-Control-Request-Headers: 

It also shows that the get request is served properly:

INFO -- : Completed 200 OK in 154ms (Views: 0.3ms | ActiveRecord: 6.3ms)

but I still get the error. Any idea what I'm doing wrong? Using nginx and unicorn. SSL is forced but the end point we're using is https, not http so there shouldn't be any redirection going on.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@zeeshan-m can you paste in the response headers?

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

@cyu Response and request headers:
screen shot 2016-10-21 at 10 15 48 am

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

@cyu Any suggestions? Still stuck on this

from rack-cors.

abepetrillo avatar abepetrillo commented on July 3, 2024

Having a very similar issue using rails-4.1.14

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@zeeshan-m Why is Request URL blank? This would be the expected result if the resource you're trying to access isn't specified in Rack::Cors

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

@cyu It's not blank, I deleted it. The request url was:

https://base_url/v2/api/partner.json

Which is the specified Rack::Cors url. On top of that, I've tried enabling debug mode which did output headers of the request. The headers however were blank.

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

@cyu Server debug output is:

D, [2016-10-25T15:04:20.265932 #1330] DEBUG -- : Incoming Headers:
  Origin: http://localhost:8100
  Access-Control-Request-Method: 
  Access-Control-Request-Headers: 
I, [2016-10-25T15:04:20.266485 #1330]  INFO -- : Started GET "/v2/api/event.json" for 8.18.218.175 at 2016-10-25 15:04:20 -0400
I, [2016-10-25T15:04:20.269529 #1330]  INFO -- : Processing by ApiController#event as JSON
I, [2016-10-25T15:04:20.389085 #1330]  INFO -- : Completed 200 OK in 119ms (Views: 0.3ms | ActiveRecord: 5.5ms)

A temporary work around for this is to add the following into your controller:

  before_action :set_headers

  def set_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'GET'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' 
  end

Modify the headers to be specific to your situation, but that should do the job.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@zeeshan-m with debug turned on in the middleware, you sure be getting a X-Rack-Cors header returned to your browser. What does that value look like?

Also, in your first post, you're getting a error message where the Origin is from port 8080, but it seems like most of your recent examples are from port 8100. Why is that?

from rack-cors.

zeeshan-m avatar zeeshan-m commented on July 3, 2024

@cyu I was testing the issue with the different apps that we have that make api calls, they run on different ports so thats most likely why you saw the 8080 vs 8100 issue.

Full response headers in debug mode are:

HTTP/1.1 304 Not Modified
Server: nginx/1.10.1
Date: Thu, 27 Oct 2016 21:07:23 GMT
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
ETag: W/"f20ae7bd4000b0d0bbfe917e48a7d6ee"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: bd0316bb-3aa9-4caf-930f-0418b54404cc
X-Runtime: 0.153243
Strict-Transport-Security: max-age=31536000
X-Rack-CORS: preflight-hit; no-path

from rack-cors.

23ranjan avatar 23ranjan commented on July 3, 2024

@yonkeltron Did you find any way out for this?
I am also facing issue with GET requests.

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@zeeshan-m weird – that X-Rack-CORS response implies that it was a preflight request (OPTIONS HTTP method). You shouldn't need that if you're doing a GET.

from rack-cors.

23ranjan avatar 23ranjan commented on July 3, 2024

@cyu Any idea why the headers are not coming for GET request ?

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@23ranjan what version of rails and rails-api are you running? What does your middleware stack look like (rake middleware)? What server are you testing against?

from rack-cors.

jtibbertsma avatar jtibbertsma commented on July 3, 2024

@cyu I'm having this issue as well. I can do a post request, but no Access-Control headers are sent with get requests.

I'm running rails 5.0.2. My middleware stack:

use Rack::Cors
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use BetterErrors::Middleware
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag

The value the X-Rack-CORS header is "miss; no-origin".

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@jtibbertsma How are you testing? The header suggests that the user agent isn't providing an Origin header.

from rack-cors.

jtibbertsma avatar jtibbertsma commented on July 3, 2024

I'm using Postman

from rack-cors.

jtibbertsma avatar jtibbertsma commented on July 3, 2024

Ok, it's working from localhost now, I just had to fix my settings :)

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@jtibbertsma ok – FYI Postman doesn't send the required Origin header to trigger a CORS response

from rack-cors.

jtibbertsma avatar jtibbertsma commented on July 3, 2024

It works for post requests tho

from rack-cors.

soynog avatar soynog commented on July 3, 2024

I came across a similar issue: OPTIONS requests being sent from my Angular front end weren't getting CORS headers attached by rack-cors. Setting headers: :any seems to have solved the problem, vs. headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-User-Token, X-User-Email' or ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'X-User-Token', 'X-User-Email']

Seems like possibly because I was missing these two headers (which were in the OPTIONS request but not the other requests: Access-Control-Request-Headers, Access-Control-Request-Method

from rack-cors.

thebravoman avatar thebravoman commented on July 3, 2024

No Access-Control-Allow-Origin on my side also.

This is the configuration

  config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger })  do
      allow do
        origins "https://mysite.com/"
        resource "/api/v1/resources/*", :headers => :any, :methods => [:get, :options]
      end
    end

This is the curl request for a test

curl -I --header "Origin: https://mysite.com" https://www.myothersite.com/api/v1/resources/393.json

This is the output in the log on the server side:

heroku[router]: at=info method=HEAD path="/api/v1/resources/393.json" host=www.myothersite.com
Incoming Headers:
   Origin: https://mysite.com
   Access-Control-Request-Method: 
   Access-Control-Request-Headers: 

This is the curl response

HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
Date: Tue, 06 Feb 2018 14:29:03 GMT
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Etag: W/"2ba14ede7ef89cbe92bc6b6ac94ecf98"
Cache-Control: max-age=0, private, must-revalidate
Set-Cookie: ahoy_visitor=e7744ebf-5f88-4378-81d0-edf7dc86f138; path=/; expires=Thu, 06 Feb 2020 14:29:03 -0000
Set-Cookie: ahoy_visit=d4e0722f-642f-4a14-8383-e9d1294732e4; path=/; expires=Tue, 06 Feb 2018 18:29:03 -0000
X-Request-Id: 882deeb4-44df-49b9-a225-26b2d58a7889
X-Runtime: 0.022971
Vary: Accept-Encoding, Origin
X-Rack-Cors: miss; no-origin
Via: 1.1 vegur

It is not setting the Access-Controll-Allow-Origin

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@thebravoman the miss; no-origin means that the middleware never received the Origin: - maybe it's getting stripped out by something running upstream?

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@thebravoman sorry no-origin can also mean that the no matching origin.

Since your origin is 'https://mysite.com/', that does an exact string match with the Origin header. The origin in your curl command should therefore be 'https://mysite.com' (minus trailing slash), or you should change the configured origin to not have the trailing slash.

from rack-cors.

thebravoman avatar thebravoman commented on July 3, 2024

@cyu Thanks. This seems to be the problem. Quite funny. I spent a lot of time on this.

from rack-cors.

thebravoman avatar thebravoman commented on July 3, 2024

from rack-cors.

LucasCioffi avatar LucasCioffi commented on July 3, 2024

I was able to fix the error locally and on Heroku. I was getting a 401 when making a GET request through the browser.

I was able to make progress in figuring out the problem by making the same request using Postman. That showed me the body of the response which wasn't visible in the log when debug mode was on: "You need to sign in or sign up before continuing."

Seeing an unexpected message about authentication helped me realize that I had a typo in my URL (/admin/widgets instead of /widgets), and I was requesting a route in my app that was protected by ActiveAdmin.

I'm writing this explanation, because people can also get in this same situation of receiving 401s and thinking it's related to rack-cors if they are using Devise and they are requesting a route protected by before_action :authenticate_user!

This is what worked for me in application.rb:

config.middleware.insert_before ActionDispatch::Static, Rack::Cors, debug: true do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end

from rack-cors.

jattoabdul avatar jattoabdul commented on July 3, 2024

Has there been any fix or workaround for this error? I am having a similar error where I am getting No route (404) error when making an OPTIONS requests to any of my endpoints.

I am using rails v6, rack-cors ~>1.0

in my application.rb I have

config.middleware.insert_before 0, Rack::Cors, debug: true do
      allow do
        origins '*'

        resource '*', headers: :any, expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end

from rack-cors.

cyu avatar cyu commented on July 3, 2024

@jattoabdul how are you testing this? Are you sure your requests are passing in an Origin header?

from rack-cors.

alispat avatar alispat commented on July 3, 2024

Same issue here :(

from rack-cors.

cyu avatar cyu commented on July 3, 2024

I'm closing this issue because there are different issues at play (some legit, some invalid).

If you're still having problems. Please create a new issue and provide the specifics.

from rack-cors.

swathi-ally avatar swathi-ally commented on July 3, 2024

Has there been a fix or workaround for this?
I have specified a random origin, but still, all the origins are allowed, instead of CORS error.
Rails: 5.2.
CORS: 1.1.1

from rack-cors.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.