How to be aple to POST, PUT and DELETE from Backbo

2019-06-08 10:12发布

问题:

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