How to properly configure CORS POST request with Backbone.js

I have an application where the backend is hosted on a different server than the front end. The backend is already configured to allow front-end requests and we confirmed this with a POST request using the jQuery method $.ajax

. However, I would really like to customize the save method on the Backbone model to do the same or something similar so that it works with Backbone as well. This is the code I have right now:

$.ajax({
    type: 'POST',
    url: 'https://someurl.com/controller',
    crossDomain: true,
    data: '{"some":"json"}',
    dataType: 'json',
    success: function(responseData) {
        // handle success
    },
    error: function (error) {
        // handle error
    }
});

      

I would like to do something like this:

myModel.save(null, function(data){
    // handle response appropriately
});

      

could you help me?

+3


source to share


2 answers


I ended up creating a custom save method that does the same thing as before, but at least it's better encapsulated since the method is defined in the model.



        saveFunction: function(attributes, callback) {
            $.ajax({
                type: 'POST',
                url: this.url,
                dataType: 'json',
                crossDomain: true,
                data: attributes
            }).done(function( data ) {
                   callback(data);
            }); 
        }

      

0


source


You can override Model.sync

to customize the requests sent to your server. For example, to add an attribute crossdomain: true

:



var M = Backbone.Model.extend({
    url: 'https://someurl.com/controller',

    sync: function(method, model, options) {
        _.defaults(options || (options = {}), {
            crossDomain: true
        });

        return Backbone.sync.call(this, method, model, options);
    }
});

var m = new M();
m.save();

      

0


source







All Articles