Express redirect sending page as data to success of angular $http instead of redirecting to the page
本问题已经有最佳答案,请猛点这里访问。
当用户被验证后,客户端得到
客户端呼叫:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $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'); } }); |
服务器端控制器方法:
1 2 3 4 5 6 7 8 9 10 | 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); } }); }; |
app.js中的路线:
1 2 3 4 | app.get('/home', function (req, res) { var path = require('path'); res.sendFile(path.resolve('server/views/home.html')); }); |
您可以将重定向逻辑移动到客户机。
客户:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $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'); }); |
服务器:
1 2 3 4 5 6 7 8 9 10 11 | 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); } }); }; |