Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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: '[email protected]',
           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.

like image 257
Tarun Avatar asked Dec 08 '22 10:12

Tarun


2 Answers

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.

like image 118
Eugene Glova Avatar answered Feb 16 '23 09:02

Eugene Glova


Update initialize to :

    initialize: function() {    
      var myUser = {
           userName: '[email protected]',
           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.

like image 40
Niranjan Borawake Avatar answered Feb 16 '23 08:02

Niranjan Borawake