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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With