简体   繁体   中英

enable cors on a rails application

On my application_controller.rb I have the following code

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :init_headers

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

I am also using the a chrome plugin Allow-Control-Allow-Origin when I am running the angularjs front end I am getting the following error. XMLHttpRequest cannot load Response for preflight has invalid HTTP status code 404

Firstly, I'd highly recommend using the Rack-CORS gem .

Instead of messing around with your ApplicationController , you'll be able to run rules from your config settings.

It handles CORS from the middleware, so you'll be able to create app-wide rules as follows:

#config/application.rb
...
config.middleware.insert_before 0, "Rack::Cors" do
   allow do
      origins '*'
      resource '*', :headers => :any, :methods => [:get, :post, :options]
   end
end
...

Their documentation is very good and self explanatory.

--

In regards your error, the 404 code suggests that you're trying to access a resource which simply doesn't exist. Either the URL or the routes won't be picking up the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM