如何从控制器页面重定向页面? - Nodejs

时间:2017-01-31 06:08:32

标签: angularjs node.js express

登录控制器 -

 var myapp = angular.module('myApp', ['ngRoute']);

    myapp.config(["$routeProvider", function($routeProvider) {
        $routeProvider

        .when('/addusers', {
            controller: 'addusersctrl',
            templateUrl: '../views/addusers.html'
        })
        .otherwise({
            redirectTo: '/'
        });

    }]);

    myapp.controller('loginctrl', ['$scope', '$route', '$http', '$routeParams', '$location', 
                     function($scope, $route, $http, $routeParams, $location) {
        console.log("im a controller");



        $scope.login = function() {
            //console.log($scope.user);

            // $http.post('/login',$scope.user).success(function(response){
            //  console.log(response);
            // });

            $http({
                  method: 'post',
                  url: '/login',
                  data: $scope.user 
                }).then(function successCallback(response) {
                    // this callback will be called asynchronously
                    // when the response is available
                     console.log('Inside controller');

                    // console.log(response.data+" "+location);
                    //$window.location.href = 'addusers.html';
                    //window.location.href = '/views/addusers.html';
                     $location.path("/addusers");
                }, function errorCallback(response) {

                    console.log(response.data);
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });

        };
    }]);


    myapp.controller('addusersctrl',['$scope','$http',function($scope,$http){
        console.log("im a controller");



        $scope.login = function() {
            //console.log($scope.user);

            // $http.post('/login',$scope.user).success(function(response){
            //  console.log(response);
            // });

            $http({
                  method: 'post',
                  url: '/login',
                  data: $scope.user 
                }).then(function successCallback(response) {
                    // this callback will be called asynchronously
                    // when the response is available

                    console.log(response.data);
                    //$window.location.href = 'addusers.html';

                }, function errorCallback(response) {

                    console.log(response.data);
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });

        };
    }]);

Server.js -

     var express = require('express')
        var app = express()
        var mongojs = require('mongojs');
        var db = mongojs('userlogin',['userlogin']);
        var bodyParser = require('body-parser');
        //
        var exphbs = require('express-handlebars');
        var path = require('path');
        var routes = require('./routes/index');
        var users;
        users = require('./routes/users');
        app.set('views', path.join(__dirname, 'views'));
        app.engine('html', exphbs({defaultLayout:'layout'}));
        app.set('view engine', 'html');
        app.use(express.static(path.join(__dirname,'public')));
        app.use(bodyParser.json());
        //var Client = require('node-rest-client').Client;
        //var client = new Client();
         var request = require('request');




        app.post('/login',function(req, res){
            console.log(req.body);

        // // direct way uncomment this and try to http request

        //  client.post("http://192.168.1.6:8080/RestTGRP/TGRP/checkAPI", function (data, response) {
        //     // parsed response body as js object 
        //     //console.log(data);
        //     // raw response 
        //     console.log(response);
        //     //res.send(response);
        // });

            // this is another method to call client 

            var options = {
                uri : 'http://192.168.1.6:8080/RestTGRP/TGRP/checkAPI',
                method : 'post'
            }; 
            var resss = '';
            request(options, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    resss = body;
                }
                else {
                    resss = 'Not Found';
                }
                console.log(body);
                //res.json(resss);

            });



// this is to validate the user



    db.collection('userlogin').findOne({name: req.body.name},       function(err, user) {
                    console.log('inside validation');
                    console.log(err);
                    console.log(user);
                    // In case the user not found   
                    if(!user) {
                      console.log('THIS IS ERROR RESPONSE')
                      res.json("user not found!")
                    }
                    else{
                        console.log('User found '); 

                        if (user.password === req.body.password){
                          console.log('User and password is correct');
                          // alert('inside user login'+res);
                          res.json("login successfully");
                          //res.render('addusers');
                        } else {
                          console.log("Credencials wrong");
                          res.json("wrong password");
                        }
                    }              
             });
            });

            app.use('/', routes);
            app.use('/users', users);

            app.listen(8000, function(){
                console.log("running successfully in 8000");




            });

每当我们尝试从登录页面导航到addusers页面时,我们都会收到404 Page Not Found Error。 如何从控制器页面重定向页面?

1 个答案:

答案 0 :(得分:1)

很可能是您在路由配置中提供templateUrl的方式。我的建议是找出你的docroot,它很可能是nodejs的项目文件夹,并提供了相对于templateUrl中docroot的完整路径,而不是" ../"风格表现。您要做的是提供相对于登录控制器的templateUrl。

例如,如果您的项目结构是:

 nodeproject/
         |-> js/
         |-> loginPage/    
                |-> views/

routeConfig中的templateUrl将是:

myapp.config(["$routeProvider", function($routeProvider) {
    $routeProvider

    .when('/addusers', {
        controller: 'addusersctrl',
        templateUrl: '/loginPage/views/addusers.html'
    })
    .otherwise({
        redirectTo: '/'
    });

}]);