когда я обновляю страницу, не страница загружается. Angularjs + Nodejs

html angularjs node.js express

750 просмотра

3 ответа

54 Репутация автора

Когда я перезагружаю страницу нажатием клавиши F5, страница не перезагружается. Я использую Node.js, Express Js и AngularJS.

index.html

    <!DOCTYPE html>
    <html lang="es-ar">
    <head>
        <title>My web</title>
        <meta charset="utf-8"/>

        <meta name="viewport" content="width=device-width, initial-scale=1" /> 
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
        <script type="text/javascript" src="https://code.angularjs.org/1.4.7/angular-animate.min.js"></script>
        <script type="text/javascript" src="https://code.angularjs.org/1.4.7/angular-cookies.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
        <script type="text/javascript" src="https://code.angularjs.org/1.4.7/angular-resource.min.js"></script>
        <script type="text/javascript" src="https://code.angularjs.org/1.4.7/angular-sanitize.min.js"></script>
        <script type="text/javascript" src="https://code.angularjs.org/1.4.7/angular-touch.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
        <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css' />
        <link href="stylesheets/main.css" rel="stylesheet" type="text/css"/>
        <!--Maps-->
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBcKGv4lLvSO6F8dKq976CT_zQPiRVcDRQ&sensor=false"></script>
        <script type="text/javascript" src="js/vendors/leaflet.js"></script>
        <script type="text/javascript" src="js/vendors/angular-simple-logger.js"></script>
        <script type="text/javascript" src="js/vendors/ui-leaflet.min.js"></script>
        <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css" />

        <base href="/">
    </head>
    <body class="backgroundGrayLight" ng-app="Index" ng-controller="indexController">
<nav class="navbar navbar-default startNav" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false" ng-click="btnCollapseNavBar()">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">WebSiteName</a>
            </div>

            <div class="collapse navbar-collapse" id="navbar-collapse">

                <form class="navbar-form navbar-left formSearch" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control search" placeholder="Search">
                    </div>
                    <a class="btnSearch" href="" close-collapse><span class="glyphicon glyphicon-search"></span></a>
                </form>

                <ul class="nav navbar-nav navbar-right" id="btnSignRoot" ng-show="viewBtnEnter">

                    <li uib-dropdown role="presentation">
                        <a uib-dropdown-toggle ng-show="viewBtnEnter" id="formLogin"><span class="glyphicon glyphicon-log-in"></span> Iniciar sesión</a>
                        <!-- action="/login" method="post"  -->
                        <form class="form-horizontal uib-dropdown-menu loginForm" aria-labelledby="formLogin">
                            <div class="form-group">
                                <label for="inputEmail" class="col-sm-2 control-label">Email</label>
                                <div class="col-sm-10">
                                    <input name="email" type="email" class="form-control" id="inputEmail" ng-model="formData.email" placeholder="Email">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputPassword" class="col-sm-2 control-label">Password</label>
                                <div class="col-sm-10">
                                    <input name="password" type="password" class="form-control" id="inputPassword" ng-model="formData.password" placeholder="Password">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox"> Remember me
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <div class="recoveryPassword">
                                        <a class="text-center" href="/recoveryPassword" close-collapse>Olvidé mi contraseña</a>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <div class="error">
                                        <p class="text-center" ng-show="msgErrorLogin" close-collapse>Nombre de usuario o contraseña incorrecta</p>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <button class="btn btn-primary submitLogIn" ng-click="login()" close-collapse>Iniciar</button>
                                </div>
                            </div>
                        </form>
                    </li>

                    <li role="presentation"><a href="/signin" ng-show="viewBtnEnter" close-collapse><span class="glyphicon glyphicon-user"></span> Registrarse</a></li>

                </ul>
            </div>
        </div>
    </nav>

    <nav class="navbar navbar-inverse menu" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-menu" aria-expanded="false" ng-click="btnCollapseMenu()">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <collapse-left></collapse-left>
            </div>

            <div class="collapse navbar-collapse menuNav" id="navbar-collapse-menu">

                <ul class="nav navbar-nav navbar-right menuRight">

                    <li role="presentation">
                        <a class="btn" href="/contact" close-collapse style="background-color: #000;">Contacto</a>
                    </li>
                    <li uib-dropdown role="presentation">
                        <a uib-dropdown-toggle class="btn" href="" style="background-color: #000;" id="idMyAccountDropdown">Mi cuenta</a>
                        <ul class="uib-dropdown-menu optionMyAccount" aria-labelledby="idMyAccountDropdown">
                            <li><a href="/manageAccount" close-collapse>Administrar mi cuenta</a></li>
                            <li class="divider"></li>
                            <li><a href="" ng-click="loadModalCreateShop()" close-collapse>Crear comercio</a></li>
                            <li><a href="/manageMyShops" close-collapse>Administrar mis negocios</a></li>
                            <li class="divider"></li>
                            <li><a href="/manageWeb" close-collapse>Administrar web</a></li>
                            <li><a href="/logout" close-collapse>Cerrar sesión</a></li>
                        </ul>
                    </li>

                </ul>
            </div>
        </div>
    </nav>

    <div class="backgroundGrayLight">
        <div ng-view></div>
    </div>

    <footer class="footer" ng-controller="yearCopyright">
        <div class="container-fluid">
            <p class="text-center">&copy; {{year}}</p>
        </div>
    </footer>

    <!-- Modules -->
    <script type="text/javascript" src="js/app.js"></script>

    <!-- Controllers -->
    <script type="text/javascript" src="js/controllers/indexController.js"></script>
    <script type="text/javascript" src="js/controllers/mainController.js"></script>
    <script type="text/javascript" src="js/controllers/formSignInController.js"></script>
    <script type="text/javascript" src="js/controllers/contactController.js"></script>
    <script type="text/javascript" src="js/controllers/recoveryPasswordController.js"></script>
    <script type="text/javascript" src="js/controllers/manageAccountController.js"></script>
    <script type="text/javascript" src="js/controllers/pModalMsgInstanceController.js"></script>
    <script type="text/javascript" src="js/controllers/homepageController.js"></script>
    <script type="text/javascript" src="js/controllers/shopsController.js"></script>
    <script type="text/javascript" src="js/controllers/shopSelectedController.js"></script>
    <script type="text/javascript" src="js/controllers/createShopController.js"></script>
    <script type="text/javascript" src="js/controllers/loadImagesController.js"></script>
    <script type="text/javascript" src="js/controllers/loadVideoController.js"></script>
    <script type="text/javascript" src="js/controllers/shopPaymentController.js"></script>
    <script type="text/javascript" src="js/controllers/manageMyShopsController.js"></script>
    <script type="text/javascript" src="js/controllers/editShopController.js"></script>
    <script type="text/javascript" src="js/controllers/manageWebController.js"></script>

    <!-- Directives -->
    <script type="text/javascript" src="js/directives/onErrorSrc.js"></script>
    <script type="text/javascript" src="js/directives/inputName.js"></script>
    <script type="text/javascript" src="js/directives/inputLastName.js"></script>
    <script type="text/javascript" src="js/directives/inputUserName.js"></script>
    <script type="text/javascript" src="js/directives/inputEmailWithRepeat.js"></script>
    <script type="text/javascript" src="js/directives/inputPassword.js"></script>
    <script type="text/javascript" src="js/directives/inputPasswordWithRepeat.js"></script>
    <script type="text/javascript" src="js/directives/inputEmail.js"></script>
    <script type="text/javascript" src="js/directives/inputSubject.js"></script>
    <script type="text/javascript" src="js/directives/inputComment.js"></script>
    <script type="text/javascript" src="js/directives/pModal.js"></script>
    <script type="text/javascript" src="js/directives/collapseLeft.js"></script>
    <script type="text/javascript" src="js/directives/closeCollapse.js"></script>
    <script type="text/javascript" src="js/directives/inputShopName.js"></script>
    <script type="text/javascript" src="js/directives/inputAddress.js"></script>
    <script type="text/javascript" src="js/directives/inputAddressNumber.js"></script>
    <script type="text/javascript" src="js/directives/inputProvinceCity.js"></script>
    <script type="text/javascript" src="js/directives/inputPhoneNumber.js"></script>
    <script type="text/javascript" src="js/directives/inputLinkWebsite.js"></script>
    <script type="text/javascript" src="js/directives/shopCommentaryMain.js"></script>
    <script type="text/javascript" src="js/directives/inputNewCommentaryShop.js"></script>

    <!-- Services -->
    <script type="text/javascript" src="js/services/serveCategories.js"></script>
    <script type="text/javascript" src="js/services/serveShopData.js"></script>

    <!-- Vendors -->
    <script type="text/javascript" src="js/vendors/ui-bootstrap-tpls-0.14.3.min.js"></script>
    <script type="text/javascript" src="js/vendors/ng-file-upload-shim.min.js"></script>
    <script type="text/javascript" src="js/vendors/ng-file-upload.min.js"></script>
    <script type="text/javascript" src="js/vendors/checklist-model.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

</body>
</html>

indexController.js

app.config(['$httpProvider', '$routeProvider', '$locationProvider', function ($httpProvider, $routeProvider, $locationProvider) {    
    $routeProvider
        .when('/main', {
            templateUrl: 'views/main.html',
            controller: 'carouselImg'
        })

        .when('/signin', {
            templateUrl: 'views/signIn.html',
            controller: 'formSignInController'
        })

        .when('/contact', {
            templateUrl: 'views/contact.html',
            controller: 'contactController'
        })

        .when('/recoveryPassword', {
            templateUrl: 'views/recoveryPassword.html',
            controller: 'recoveryPasswordController'
        })

        .when('/manageAccount', {
            templateUrl: 'views/manageAccount.html',
            controller: 'manageAccountController'
        })

        .when('/homepage', {
            templateUrl: 'views/homepage.html',
            controller: 'homepageController'
        })

        .when('/shop/:itemId/cat/:categoryId', {
            templateUrl: 'views/shops.html',
            controller: 'shopsController'
        })

        .when('/shop/:shopName', {
            templateUrl: 'views/shopSelected.html',
            controller: 'shopSelectedController'
        })

        .when('/manageMyShops', {
            templateUrl: 'views/manageMyShops.html',
            controller: 'manageMyShopsController'
        })

        .when('/manageMyShops/id/:shopId', {
            templateUrl: 'views/editShop.html',
            controller: 'editShopController'
        })

        .when('/manageWeb', {
            templateUrl: 'views/manageWeb.html',
            controller: 'manageWebController'
        })

        .otherwise({
            redirectTo: '/main'
        });

    $locationProvider.html5Mode(true); }]);

express.js

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var passport = require('passport');
var flash = require('connect-flash');
var path = require('path');
var favicon = require('serve-favicon');
var router = express.Router();

module.exports = function(io) {

    var app = express();

    /**
    * Connect to our database
    */

    require(__dirname + '/passport')(passport);

    /**
    * Set up our express application
    */
    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(morgan('dev'));
    app.use(cookieParser());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());

    /* 
    * Required for passport
    */
    app.use(session({
        secret: 'vidyapathaisalwaysrunning',
        resave: true,
        saveUninitialized: true
    })); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session

    /*
    * Routes
    */
    require('../app/routes/index.server.routes')(app, passport, router, io); // load our routes and pass in our app and fully configured passport

    /**
    * Development Settings
    */
    if ('development' == app.get('env')) {
        // This covers serving up the index page
        app.use(express.static(path.join('./public')));

        app.use(function (err, req, res, next) {
            console.error(err.stack);
            res.send(500, 'Something broke!');
        });
    }

    /**
    * Production Settings
    */
    if ('production' == app.get('env')) {
        app.use(express.static(path.join('./public')));
    }

    //module.exports = app;
    return app;
}

index.server.routes.js

    app.get(['/homepage', '/recoveryPassword', '/manageAccount', '/shop/:itemId/cat/:categoryId', '/shop/:shopName', '/manageMyShops', '/manageMyShops/id/:shopId', '/manageWeb'], isLoggedIn, function (req, res) {
        //res.redirect(here req.path) -> Infinite loop
        res.end();    
    });

    function isLoggedIn(req, res, next) {
        // if user is authenticated in the session, carry on
        if (req.isAuthenticated()) {
            return next();
        }

        // if they aren't redirect them to the home page
        res.redirect('/');
    }
  • приложение (на стороне сервера)
    • контроллеры
    • маршруты
  • общественности
    • /картинки
    • / JS
    • / таблицы стилей
    • /Просмотры
    • index.html

Ошибка происходит со всеми страницами. Я хочу сделать пользовательский контроль для определенных разделов сайта. Когда я нажимаю клавишу f5, если пользователь вошел в систему, вы будете перенаправлены на страницу, к которой хотите получить доступ. пример: / homepage + f5 -> isLoggedIn (...)? / homepage: /index.html

Благодарю.

Автор: Z. Danilo Источник Размещён: 19.07.2016 12:21

Ответы (3)


1 плюс

345 Репутация автора

Поскольку не так уж и много, я сначала вычеркну очевидное исправление.

Ваш маршрут не настроен для обработки одностраничного приложения.

Маршрутизатор Angular меняет представления в индексной странице и обратно, когда вы перемещаетесь по ней, но на самом деле вы никогда не покидаете эту первую страницу. Это желаемое поведение для одностраничного приложения.

Если вы обновляете страницу, например index.com/go/to/path, вы сообщаете браузеру, что нужно перейти по этому пути index.com/go/to/path.

Angular не имеет об этом никакого представления, и его маршрутизация обрабатывает только пути, найденные на index.com.

если вы используете nginx, добавьте это в ваше местоположение:

try_files $uri $uri/ /index.html;

Решение будет похоже, если не то же самое, в Apache (не знаю, с моей головы).

Он перенаправляет все эти app.com/paths/more/paths на app.com/

Там angular прочитает / paths / more / paths и загрузит правильное представление.

Автор: Dreamlines Размещён: 19.07.2016 01:34

0 плюса

1359 Репутация автора

попробуй это

res.sendFile(path.join(__dirname, '/public', 'index.html'));

он будет перенаправлен на index.html при нажатии клавиши f5.

Автор: chirag Размещён: 19.07.2016 06:59

0 плюса

106 Репутация автора

Попробуй это

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/www'));

app.all('/*', function(req, res, next) {
  // Just send the index.html for other files to support HTML5Mode
  res.sendFile('www/index.html', { root: __dirname });
});
Автор: puneet Размещён: 10.02.2017 12:08
Вопросы из категории :
32x32