Backbone model.save returning error while server sending 200:OK

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I have defined the following Backbone Model:

var User = Backbone.Model.extend({         url: "/login",         contentType: "application/com.example.auth+json",          defaults: {             userName: '',             password: ''         },          validate: function(attrs){             if(!attrs.userName){                 return 'Please fill username field.'             }             if(!attrs.password){                 return 'Please fill password field.'             }         }     });

I am using the following code in my Backbone.View

// ...     initialize: function() {            this.model = new User();        myUser = {            userName: 'labuser1@example.com',            password: 'abcd_1234',        };     }      onSubmit: function() {          this.model.save(myUser, {             success: function () {                 alert('You are authenticated');                 Backbone.trigger('Authenticated', {source: 'LOGIN'});             },             error: function (model, error) {                 alert('Error: " + error);             }         });     }

I am receiving the following response from backend, no response data is send only status code is returned:

Request URL : https://server/login  Request Method:POST  Status Code:200 OK

But I am getting 'Error: [object Object]' printed. Why it is not reaching success handler, inspite of the server authenticating the user successfully. Please advise how to fix this in frontend / backend if required.

回答1:

You can either use this code dataType: 'text' to fix it

... this.model.save(myUser, {     dataType: 'text',     success: function () { ...

or fix server side by setting correct Content-type header to application/json value.



回答2:

Update initialize to :

    initialize: function() {           var myUser = {            userName: 'labuser1@example.com',            password: 'abcd_1234',        };       this.model = new User(myUser);     }

You need to initialize your model hereand then in onSubmit function you can directly save it :

onSubmit: function() {          this.model.save(null, {             success: function () {                 alert('You are authenticated');                 Backbone.trigger('Authenticated', {source: 'LOGIN'});             },             error: function (model, error) {                 alert('Error: " + error);             }         });     }

NOTE : model.save should be used to create a new model and persist it at backend and not to authenticate. You might want to make a different ajax call for this.



回答3:

In case of PUT (model update) make sure to return status 204 (no-content) instead of 200 (ok) if your response does not contain any content.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!