So in login page I am sending credentials from angular to express through get request.What I wanna do is that if found in database,send response and handle it in angular else if not found in db I want express to send error response and handle it angular error response function but my code isnt working.
Angular controller:
myapp.controller('therapist_login_controller', ['$scope', '$localStorage', '$http', function($scope, $localStorage, $http) { $scope.login = function() { console.log($scope.username + $scope.password); var data = { userid: $scope.username, password: $scope.password }; console.log(data); $http.post('/api/therapist-login', data) .then( function(response) { // success callback console.log("posted successfully"); $scope.message = "Login succesful"; }, function(response) { // failure callback,handle error here $scope.message = "Invalid username or password" console.log("error"); } ); } } ]);
APP.js:
app.post('/api/therapist-login', therapist_controller.login);
Controller:
module.exports.login = function(req, res) { var userid = req.body.userid; var password = req.body.password; console.log(userid + password); Credentials.findOne({ 'userid': [userid], 'password': [password] }, function(err, user) { if (!user) { console.log("logged err"); res.status(404); //Send error response here enter code here } else { console.log("login in"); } }); }
To send the status code to the client-side, you can method chain using the . send() method. The status code 404 tells the client side that the data requested is not found.
The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.
In Node with ExpressJS you can use res.status()
to send the error:
return res.status(400).send({ message: 'This is an error!' });
In Angular you can catch it in the promise response:
$http.post('/api/therapist-login', data) .then( function(response) { // success callback console.log("posted successfully"); $scope.message = "Login succesful"; }, function(response) { // failure callback,handle error here // response.data.message will be "This is an error!" console.log(response.data.message); $scope.message = response.data.message } );
Or use instance of Error
class
response.status(code).send(new Error('description'));
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