CORS error for rails API -
i building rails api , when send request app (on different subdomain api) following response:
xmlhttprequest cannot load http://api.myapp.dev/v1/posts/create. request header field content-type not allowed access-control-allow-headers.
i don't understand why happening, since in rails controller have set headers['access-control-allow-headers'] = '*'
.
my app/routes.rb file
:
rails.application.routes.draw namespace :v1, defaults: {format: 'json'} # take care of cors match "*all", to: "api#cors_preflight_check", via: [:options] # routes posts 'posts(/index)', :to => 'posts#index' post 'posts/create' delete 'posts/:id', :to => 'posts#destroy' 'posts/show' put 'posts/:id', :to => 'posts#update' # routes post comments 'posts/:post_id/comments(/index)', :to => 'comments#index' post 'posts/:post_id/comments/create', :to => 'comments#create' delete 'posts/:post_id/comments/:id', :to => 'comments#destroy' put 'posts/:post_id/comments/:id', :to => 'comments#update' end end
my app/controllers/v1/api_controller.rb file
:
module v1 class apicontroller < applicationcontroller skip_before_filter :verify_authenticity_token protect_from_forgery with: :null_session before_filter :cors_preflight_check after_filter :cors_set_access_control_headers def cors_set_access_control_headers headers['access-control-allow-origin'] = '*' headers['access-control-allow-methods'] = '*' headers['access-control-request-method'] = '*' headers['access-control-allow-headers'] = '*' headers['access-control-max-age'] = "1728000" end def cors_preflight_check if request.method == "options" headers['access-control-allow-origin'] = '*' headers['access-control-allow-methods'] = '*' headers['access-control-request-method'] = '*' headers['access-control-allow-headers'] = '*' headers['access-control-max-age'] = '1728000' render :text => '', :content_type => 'text/plain' end end end end
what problem be?
honestly easiest thing use this , set configuration in config/application.rb file.
Comments
Post a Comment