2016-02-12 13 views
5

Kullanıcı doğrulandığında, istemciye home.html sayfasındaki home.html sayfa içeriği home.html'a yeniden yönlendirilmek yerine result sayfasından alın.

İstemci tarafı çağrı:

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

Sunucu tarafı denetleyici yöntemi: app.js içinde

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

Rota:

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

bu deneyin: res.redirect (path.resolve ('sunucu/görüntüleme/home.html')); –

+1

AJAX'tan bir tarayıcı yönlendirmesi yapamazsınız. Yeniden yönlendirilmeli ve istemcide yapılıp yapılmadığını kontrol etmelisiniz. –

+0

Yeniden yönlendirme mantığını istemciye taşımak gerçekten iyi bir uygulama mıdır ve bunun için bir geçici çözüm yok mu? – Shreyas

cevap

0

Sen müşteri için yönlendirme mantığını hareket edebiliyordu.

Müşteri:

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

Sunucu:

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); 
    } 
    }); 
}; 
İlgili konular