How to be aple to POST, PUT and DELETE from Backbone app to Rails app on different subdomains?

别说谁变了你拦得住时间么 提交于 2019-12-23 03:22:38

问题


Whick is the best way to POST, PUT and DELETE from Backbone app to Rails app on different subdomains?

I have tried to fetch some data with Backbone from the Rails app and it works. I have tried to save new content with Backbone to Rails app.

I have real problems with PUT (updating a created model in database). I don't know why, but when I do in my backbone app something like: book.save()

And the book is a model that already existis on the database, instead of sendind a PUT petition to the Rails APP, it is sending an OPTIONS petition, and whithout the data.

Ideally, I want to send a PUT petition from the Backbone app to the Rails app, so I can do something like this in my Rails app:

Book.update_attributes params[:book]

The Rails App and the Backbone app are on different subdmains on same top level domain.


回答1:


For methods that are not post or get, the client will send an OPTIONS request to determine what is allowed cross domain. You'll need two things. You'll need a way to respond with the correct response headers to tell the client that cross domain is ok. I create an after_filter in my ApplicationController since my cross domain needs are system wide.

after_filter :allow_cross_domain

def allow_cross_domain
  headers["Access-Control-Allow-Origin"] = request.env['HTTP_ORIGIN']
  headers["Access-Control-Request-Method"] = "*"
  headers["Access-Control-Allow-Methods"] = "PUT, OPTIONS, GET, DELETE, POST"
  headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type'
  headers["Access-Control-Max-Age"] = 1728000
end

Next you need to handle the options request In your routes.rb

match "*options", controller: "application", action: "options", constraints: { method: "OPTIONS" }

and in the controller that will handler the request (ApplicationController for me)

def options
  allow_cross_domain
  render :text => "", :layout => false
end


来源:https://stackoverflow.com/questions/10250233/how-to-be-aple-to-post-put-and-delete-from-backbone-app-to-rails-app-on-differe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!