Backbone Fetch Request is OPTIONS method

Jeffrey Chen picture Jeffrey Chen · Jul 2, 2012 · Viewed 12.8k times · Source

I have a Backbone Collection object with the following URL "http://localhost:8080/api/menu/1/featured". I am trying to perform a fetch operation to retrieve the collection from the url and parse it. However, on the server side, the method type that I see for this request is OPTIONS. The server is only suppose to support GET method. I am not sure how Backbone is figuring out what method type to use, and why it changes to OPTIONS method type randomly sometimes. I am using a Node.js server to process the request. This code below is pretty much what I did.

var FeaturedCollection = Backbone.Collection.extend({
    model:FeaturedContent,
    url:function () { return url_featured; },
    parse:function (response) {
        console.log(response);
        return response;
    }
});

var featuredCollection = new FeaturedCollection();
featuredCollection.fetch();

Please help, thanks!

Answer

Mauvis Ledford picture Mauvis Ledford · Oct 30, 2012

It's been awhile, but I remember coming across this before. There's two things this could be: Backbone by default tried to do RESTful API calls to your backend, this means GET, POST, PUT, and DELETE.

Many backends weren't built with real REST support and only support GET and POST. When Backbone sends a PUT or DELETE command your browser (not Backbone) automatically sends an OPTIONS request first to see if it's allowed to make these kinds of requests. If your server answers improperly this call will fail and probably Backbone won't do anything.

To get around this set Backbone.emulateHTTP = true; Or have your server properly answer OPTIONS calls. See the documentation for more info: http://backbonejs.org/#Sync-emulateHTTP

The other issue is that you're making ajax requests cross-domain / sub-domain and you need to properly enable CORS. This also includes properly answering OPTIONS requests.