Shr*_*yas 8 node.js express angularjs
当用户通过验证客户端获取的页面内容home.html
中result
,而不是重定向到home.html
.
客户端电话:
$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');
}
});
Run Code Online (Sandbox Code Playgroud)
服务器端控制器方法:
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);
}
});
};
Run Code Online (Sandbox Code Playgroud)
在app.js中路由:
app.get('/home', function (req, res) {
var path = require('path');
res.sendFile(path.resolve('server/views/home.html'));
});
Run Code Online (Sandbox Code Playgroud)
您可以将重定向逻辑移至客户端。
客户:
$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');
});
Run Code Online (Sandbox Code Playgroud)
服务器:
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);
}
});
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
848 次 |
最近记录: |