How to set Backbone.js to include model name in JS

2019-08-29 07:10发布

I've been working on a Backbone.js project that syncs to a Google App Engine REST server I've also put together. I'm using the Appengine-Rest-Server project code to enable the REST interface. IT works really well, but there is one problem. When I post a new model to it, it expects a JSON post in the form of:

{ 'modelname' : {'attribute1':'attribute','attribute2':'attribute'}}

When I use python and the requests library to POST this data to my REST server... it works fine.

Backbone.js appears to be sending POST requests without the model name a la

{'attribute1':'attribute','attribute2':'attribute'}

Now, not being an expert on what formats are 100% RESTful, I'm not sure whether my REST server is improperly configured (in which case I don't expect you guys to be able to help with the code), whether Backbone.js is improperly configured, or whether both formats are potentially RESTful and I just need to figure out how to get backbone to add in the model name.

So, to close, is one or both of these formats compatible with a truly RESTful API? If requiring the model name in the JSON is not a gross violation of making a RESTful API, does anyone know how I can make Backbone send out post requests in the proper format?

Thanks!

1条回答
男人必须洒脱
2楼-- · 2019-08-29 07:26

Most elegant way:

YourModel = Backbone.Model.extend({

   name: 'modelName',

   toJSON: function () {
       var data = {};

       data[this.name] = _.clone(this.attributes); // or Backbone.Model.prototype.toJSON.apply(this)

       return data;
   }

});

Or you can directly pass data to the options

model.save(null, {
    data: {
       // custom format
    }
});
查看更多
登录 后发表回答