12

When the user is validated the client get the page contents of home.html in result instead of redirecting to the home.html.

Client side call:

$http({ method: "post", url: "http://localhost:2222/validateUser", data: { username: $scope.username, password: $scope.password } }).then(function (result) { if (result.data && result.data.length) { alert('User validated'); } else { alert('invalid user'); } }); 

Server side controller method:

module.exports.validateUser = function (req, res) { User.find({ 'username': req.body.username, 'password': req.body.password }, function (err, result) { if (result.length) { req.session.user = result[0]._doc; res.redirect('/home'); }else{ res.json(result); } }); }; 

Route in app.js:

app.get('/home', function (req, res) { var path = require('path'); res.sendFile(path.resolve('server/views/home.html')); }); 
3
  • try this: res.redirect(path.resolve('server/views/home.html')); Commented Feb 12, 2016 at 11:14
  • 1
    You can't do a browser redirect from AJAX. You need to check if it should be redirected and do it on the client. Commented Feb 12, 2016 at 11:15
  • Is it really a good practise to move the redirection logic on client, and isn't there a workaround for same? Commented Feb 12, 2016 at 11:37

1 Answer 1

0

You could move your redirect logic to the client.

Client:

$http({ method: "post", url: "http://localhost:2222/validateUser", data: { username: $scope.username, password: $scope.password }, }).then(function (result) { alert('user validated'); window.location.replace('/home'); }).catch(function(result) { alert('login failed'); }); 

Server:

module.exports.validateUser = function (req, res) { User.find({ 'username': req.body.username, 'password': req.body.password }, function (err, result) { if (result.length) { req.session.user = result[0]._doc; res.send('OK'); } else { // responding with a non-20x or 30x response code will cause the promise to fail on the client. res.status(401).json(result); } }); }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.