无法从模板获取数据并将其传递给控制器​​Angularjs

时间:2017-07-18 11:16:20

标签: javascript angularjs mongodb express mongoose

我正在尝试进行用户身份验证,但我认为我的模板出了问题。当我和邮递员一起尝试时,它有效。首先,我对/ users / authenticate进行API调用并获取令牌。然后在获取令牌后,我向/ users / me进行另一个API调用以验证它。这是成功的,用户登录。

这是我的控制者:

    .controller('homeCtrl', ['$rootScope', '$location', '$http', '$timeout', 'Auth', function ($rootScope, $location, $http, $timeout, Auth) {
    $rootScope.loadme = false;
    $rootScope.currentPa = $location.path();
    $rootScope.$on('$routeChangeStart', function () {
        if (Auth.isLoggedIn()) {
            console.log('Success: User is logged in');
            $rootScope.isLoggedIn = true;
            Auth.getUser()
                .then(function (data) {
                    $rootScope.username = data.data.username;
                    $rootScope.email = data.data.email;
                    $rootScope.loadme = true;
                });
        } else {
            $rootScope.isLoggedIn = false;
            $rootScope.username = '';
            $rootScope.loadme = true;
        }
    });


    $rootScope.doLogin = function (loginData) {
        $rootScope.loading = true;
        $rootScope.errorMsg = false;
        console.log("TEST LOGIN");

        Auth.doLogin($scope.loginData)
            .then(function (data) {
                console.log('logging in');
                if (data.data.success) {
                    console.log('fgsgsg');
                    $rootScope.loading = false;
                    $rootScope.successMsg = data.data.message + 'Redirecting...';
                    $timeout(function () {
                        console.log('12345');
                        $location.path('/#!/');
                        $rootScope.loginData = '';
                        $rootScope.successMsg = false;
                    }, 2000);
                } else {
                    console.log("no success");
                    $rootScope.loading = false;
                    $rootScope.errorMsg = data.data.message;
                }
            })
    };

这些是服务器路由和中间件:

//User Login Route
router.post('/authenticate', function (req, res) {
User.findOne({username: req.body.username})
    .select('username email password')
    .exec(function (err, user) {
        if (err) {
            throw err;
        }

        if (!user) {
            res.json({success: false, message: 'Could not authenticate 
user'});
        } else if (user) {
            if (req.body.password) {
                var validPassword = 
user.comparePassword(req.body.password);
            }
            else {
                res.status(200).json({success: false, message: 'Please 
provide password'})
            }
            if (!validPassword) {
                res.status(200).json({success: false, message: 'Could 
not authenticate password'});
            } else {
                var token = jwt.sign({username: user.username, email: 
user.email}, secret, {expiresIn: '24h'});
                res.status(200).json({success: true, message: 'User 
authenticated', token: token});
            }
        }
        console.log(user);
    });
});


 //Middleware for decoding tokens
router.use(function (req, res, next) {
var token = req.body.token || req.body.query || req.headers['x-access-
token'];

if (token) {
    jwt.verify(token, secret, function (err, decoded) {
        if (err) {
            res.json({success: false, message: 'Token Invalid'})
        } else {
            req.decoded = decoded;
            next();
        }
    });
} else {
    res.json({success: false, message: 'No token provided'});
}
});

router.post('/me', function (req, res) {
   res.send(req.decoded);
});

最后,这是模板:

    <div ng-controller="homeCtrl">
        <form ng-submit="doLogin(loginData)">
            <label>Username:</label>
            <input class="form-control" type="text" name="username" placeholder="please enter username"
                   ng-model="loginData.username">
            <br>
            <label>Email:</label>
            <input class="form-control" type="text" name="email" placeholder="please enter email"
                   ng-model="loginData.email">
            <br>
            <label>Password:</label>
            <input class="form-control" type="password" name="password" placeholder="please enter password"
                   ng-model="loginData.password">
            <br>
            <button class="btn btn-primary" type="submit" formmethod="post">Login</button>
        </form>

1 个答案:

答案 0 :(得分:1)

您无需在dologin函数中传递loginData。只需添加语句$ scope.loginData = {};到你的控制器,并在调用它时尝试在doLogin()中打印它以查看数据是否登录到控制台。