当我刷新页面时,不会加载页面。 Angularjs + Nodejs

时间:2016-07-19 00:21:48

标签: html angularjs node.js express

按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('/');
    }
  • app(服务器端)
    • 控制器
    • 路由
  • 公共
    • /图像
    • / JS
    • /样式表
    • /视图
    • 的index.html

所有页面都会出错。 我想让用户控制网站的某些部分。 当我按f5时,如果用户已登录,则应将您重定向到您要访问的页面。例如:/ homepage + f5 - &gt; isLoggedIn(...)? / homepage:/index.html

感谢。

3 个答案:

答案 0 :(得分:1)

由于没有太大的余地,我会首先抛出明显的修复。

您的路由未设置为处理单页应用。

当您在路由中路由时,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并加载正确的视图。

答案 1 :(得分:0)

试试这个

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

当您按f5时,它将重定向到index.html。

答案 2 :(得分:0)

试试这个

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