Backbone doing POST request instead of PUT request

2019-09-02 20:06发布

问题:

I am trying to set a model's attribute to be something different. When I save the model, Backbone issues a POST request instead of a PUT request.

I read on another Stackoverflow post that Backbone uses a model's id to determine if a model is new or not. When I console.log(model), the model has an id attribute. When I console.log(model.id), it prints out undefined. How come when I do a console.log(model), the model has a id attribute, yet when I do console.log(model.id), I get back undefined?

Which way does Backbone use to determine if a model is new or not? And, how can I fix the problem? I am using backbone-tastypie.

回答1:

How did you create the model in the first place? The model's id needs to be specified in the model's data. Usually this would be returned in the server response the first time you save a new object. Once the id is set Backbone will save it with PUT instead of POST.