2016-02-12 10 views
5

Quando l'utente viene convalidato, il client ottiene il contenuto della pagina di home.html in result anziché il reindirizzamento allo home.html.

client chiamata lato:

$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 metodo di controllo lato:

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); 
    } 
    }); 
}; 

Percorso in app.js:

app.get('/home', function (req, res) { 
    var path = require('path'); 
    res.sendFile(path.resolve('server/views/home.html')); 
}); 
+0

provare questo: res.redirect (path.resolve ('assistente/views/home.html')); –

+1

Non è possibile eseguire un reindirizzamento del browser da AJAX. È necessario verificare se deve essere reindirizzato e farlo sul client. –

+0

È davvero una buona pratica spostare la logica di reindirizzamento sul client e non c'è una soluzione alternativa per lo stesso? – Shreyas

risposta

0

è possibile spostare la logica di reindirizzamento al client.

Cliente:

$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); 
    } 
    }); 
}; 
Problemi correlati