Reputation: 2014
I'm writing an app with node.js and backbone.js. However when I try to save a model it is nesting the JSON of the model inside a model dictionary.
node = new NodeModel({prop1:"value1", prop2:"value2"});
node.save();
The results of console.log(req.body); inside my node controler show...
{model: {"prop1":"value1", "prop2":"value2"} }
If i use a standard html form to post to the same node controller the results of console.log(req.body); show...
{prop1:"value1", prop2:"value2"}
How can i get the node.save(); function to post the same JSON that the regular HTML does?
Upvotes: 0
Views: 1483
Reputation: 434685
Looks like you have Backbone configured to emulate JSON:
emulateJSON
Backbone.emulateJSON = true
If you're working with a legacy web server that can't handle requests encoded as
application/json
, settingBackbone.emulateJSON = true;
will cause the JSON to be serialized under amodel
parameter, and the request to be made with aapplication/x-www-form-urlencoded
mime type, as if from an HTML form.
and the corresponding chunk of Backbone.sync
looks like this:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
//...
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
You can see the model.toJSON()
call in the first if
, the model:
prefix comes in in the second if
. You should be able to say
Backbone.emulateJSON = false;
somewhere in your application setup (after Backbone is loaded, before you try to sync anything) and the model:
business will go away.
Upvotes: 1