The origin of http: // localhost is not allowed using Access-Control-Allow-Origin Rails 3

Follow this question. How to set access control-allow-origin in webrick under rails? I can get and POST from localhost to localhost: 3000 .

However, an error occurred with DELETE and PUT

This is how I allow cross-domain access

 class ApplicationController < ActionController::Base protect_from_forgery before_filter :allow_cross_domain_access def allow_cross_domain_access response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "*" end end 

Any idea how to fix this?

+7
source share
2 answers

* not a valid value for the Access-Control-Allow-Methods response header. You need to specify the actual methods:

 response.headers["Access-Control-Allow-Methods"] = "GET, PUT, POST, DELETE" 

In addition, if your request has any custom request headers, you will also need to specify them:

 response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With" 

Finally, note that your controller must allow OPTIONS http requests. This allows you to query the preliminary CORS queries that are required when executing PUT or DELETE queries.

+11
source

This solution ( http://www.tsheffler.com/blog/?p=428 ) works for me:

 before_filter :cors_preflight_check after_filter :cors_set_access_control_headers # For all responses in this controller, return the CORS access control headers. def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' headers['Access-Control-Max-Age'] = "1728000" end # If this is a preflight OPTIONS request, then short-circuit the # request, return only the necessary headers and return an empty # text/plain. def cors_preflight_check if request.method == :options headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version' headers['Access-Control-Max-Age'] = '1728000' render :text => '', :content_type => 'text/plain' end end 

Also, maybe you want to enable CORS in your selected methods:

 before_filter :cors_preflight_check, :only => [ :my_method] after_filter :cors_set_access_control_headers, :only => [ :my_method] 

I hope this helps

+9
source

All Articles