Reputation: 13721
I am building an app in node and I'm working on the error handling aspect. I am using ajax to post data from a form to my server to be uploaded into my postgresql database. One of the constraints is the email has to be unique, otherwise it will throw an error. I was able to print the error on the server side console, but I want the error to also console.log and/or alert on the client's browser as well. Here is what I have tried:
Client side:
$("#submit").click(function() {
var data = {
first_name: $("#firstName").val(),
last_name: $("#lastName").val(),
email: $("#email").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
url: "/add",
data: data,
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('some error');
}
});
});
Server side:
router.route('/add').post(function(req, res) {
knex('users').insert({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password
}).then().catch(function(error){
console.log("ERROR ERRROR ERROR " + error) //prints on console
res.send(error);
});
});
With this code, the problem is the error function is not being called on the client side... Can someone help?
Thank you in advance!
Upvotes: 0
Views: 749
Reputation: 3664
this is exactly what the success
and error
in the ajax for. You can use that to send success or error status code. For example: res.send(400)
or res.send(200)
.
You can also send data with the response, for example res.send(400, data)
Of course you can use any other HTTP codes as you find convenient.
Now, in the
error: function(data)) {
alert('some error');
}
the alert should be triggered
Upvotes: 2