【问题标题】:response.redirect() is not working in express (NodeJS)response.redirect() 在 express (NodeJS) 中不起作用
【发布时间】:2018-07-18 07:56:50
【问题描述】:

如果用户名正确,我想从 login.html 重定向到 dashboard.html,如果不正确,则会显示警告框,我使用 express response.redirect('path') 或 response.sendFile('path') 但是没有人在这里工作。 我使用 angularJs 作为前端,在后端使用 nodeJs 的 express 模块。

快递路线代码:

    module.exports = function(app,db,path){
        app.post('/student-login', function (request, response) {
        var user = request.body;
        if(user.username == "abhinav")
        {   
            response.redirect('/views/dashboard.html');
            response.end();
        }
        else{
            response.send("Wrong username");
            response.end();
        }
   });
}

AngularJs 代码:

angular.module('loginService',[])
.service('loginService',function($http){
        return {
            sendStudent : function(data){
            return $http.post('/student-login',data)
            .then(function(response){
                    return response.data;
                });
              }         
            }
});

AngularJs 控制器代码:

if ($scope.myForm.$valid)
            loginService.sendStudent($scope.studentData)
            .then(function(data){
                if(data=="Wrong username")
                alert(data);
            });

开发者选项 > 网络:

【问题讨论】:

    标签: angularjs node.js express


    【解决方案1】:

    正如您在 Network 选项卡中所见,浏览器确实向 /views/dashboard.html 路由发出请求。这意味着重定向正在工作。您没有得到预期行为的原因是您需要导航到该页面(现在您只是在加载页面的内容)。

    我建议将重定向逻辑从 express 转移到前端,并使用 http 状态代码来指示登录错误。

    快递代码:

    module.exports = function(app,db,path){
        app.post('/student-login', function (request, response) {
        var user = request.body;
        if (user.username == "abhinav") {   
            response.sendStatus(200);
        } else {
            response.sendStatus(401);
        }
    });
    }
    

    AngularJS 控制器代码:

    if ($scope.myForm.$valid) {
       loginService.sendStudent($scope.studentData).then(() => {
           // login successful, response status is 200
           location.href = '/views/dashboard.html'
       }).catch(response => {
           if (response.status === 401) {
               alert("Wrong username")
           } else { 
               alert("Some other error") 
           }
       })
    }
    

    我使用location.href 作为示例只是因为我不熟悉 angularjs 路由。它将重新加载整个页面,如果您想避免这种情况,请使用 angularjs 路由器提供的 API。

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2017-04-09
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多