Reputation: 3311
Edit, updated @ the bottom
Two domains:
Rails-api: http://localhost:3000/
/config/application.rb contains
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
}
BackboneJS: http://local.team.com/ main.js contains:
require([
'app/App',
'backbone',
'app/Router',
'bootstrap'
],
function (app, Backbone, Router) {
"use strict";
Backbone.Model.prototype.idAttribute = "_id";
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.url = "http://localhost:3000/" + options.url;
console.log('url = ', options.url)
});
window.MyApp = app;
MyApp.start();
new Router();
Backbone.history.start();
});
When a backbone model fetch is sent:
url = http://localhost:3000/users main.js:45
OPTIONS http://localhost:3000/users 404 (Not Found) jquery-1.9.0.js:8489
OPTIONS http://localhost:3000/users Origin http://local.team.com is not allowed by Access-Control-Allow-Origin. jquery-1.9.0.js:8489
XMLHttpRequest cannot load http://localhost:3000/users. Origin http://local.team.com is not allowed by Access-Control-Allow-Origin. local.team.com/:1
At this point I'm just completely confused on which end is at fault here, I would assume Backbone. Any help greatly appreciated.
* update *
I'm now using the Rails-CORS gem. It works for get requests. In my config/application.rb I have:
# https://github.com/cyu/rack-cors
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options]
end
end
GET requests, return 100% fine, no issue, post requests result in:
XMLHttpRequest cannot load localhost:3000/users. Origin http://local.team.com is not allowed by Access-Control-Allow-Origin.
Upvotes: 0
Views: 462
Reputation: 81
You have to handle additional request in your Users controller. The method type is OPTIONS. I guess you already handle GET request (index action).
Yes, the browser sends two HTTP requests. First is OPTIONS. Second is the POST or GET, the one you defined in Ajax request.
Upvotes: 1