Backbone model.save() is causing POST not PUT

后端 未结 5 655
天涯浪人
天涯浪人 2021-01-12 13:35

I have a Backbone model:

var User = Backbone.Model.extend({
  idAttribute: \'_id\',

  url: \'/api/user\',

  defaults:
    { username: \'\'
    }
});
         


        
5条回答
  •  灰色年华
    2021-01-12 14:15

    The server response must be in this way:

    {
      _id : 111
    }
    

    Because you set _id as the primary key. When model is fetched verify the value of _id it must have a value: console.log( model.get('_id') );

    My thought is that you set in your backbone model '_id' as primary key, but service is returning you 'id'

    Update: Adding sample code of normal behavior:

    var UserModel = Backbone.Model.extend({
      idAttribute: '_id',
    
      url: '/api/user',
    
      defaults:
        { username: ''
        }
    });
    user = new UserModel({_id : 20});
    user.save();
    user = new UserModel();
    user.save();
    

    Output: PUT /api/user 405 (Method Not Allowed) POST /api/user 404 (Not Found)

    Check how the first instance of the Model has an id and it tries to do the PUT but the other POST. I cannot reproduce your issue, so my thought is that the problem is on your server response.

提交回复
热议问题