【问题标题】:Express redirect sending page as data to success of angular $http instead of redirecting to the page [duplicate]将发送页面作为数据快速重定向到角度 $http 的成功,而不是重定向到页面 [重复]
【发布时间】:2016-05-23 11:46:33
【问题描述】:

当用户被验证时,客户端在result 中获取home.html 的页面内容,而不是重定向到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');
    }
});

服务器端控制器方法:

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 中的路由:

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

【问题讨论】:

  • 试试这个:res.redirect(path.resolve('server/views/home.html'));
  • 您不能从 AJAX 进行浏览器重定向。您需要检查它是否应该被重定向并在客户端上执行。
  • 在客户端移动重定向逻辑真的是一个好习惯吗?没有解决方法吗?

标签: angularjs node.js express


【解决方案1】:

您可以将重定向逻辑移至客户端。

客户:

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

服务器:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多