简体   繁体   中英

How to redirect a page from controller page? - Nodejs

Login Controller -

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




            });

Whenever we are trying to navigate from login to addusers page, we are getting 404 Page Not Found Error. How to redirect a page from controller page?

It is most likely the way you have provided the templateUrl in the route configuration. My suggestion would be to figure out your docroot, it is most likely the project folder in case of nodejs and provide a complete path relative to the docroot in the templateUrl and not the "../" style representation. What you are trying to do is provide the templateUrl relative to the login controller.

For example if your project structure is:

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

Your templateUrl in the routeConfig would be:

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

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

}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM