node.js - URL 在浏览器刷新时发生更改($routeProvider 用于客户端路由)

标签 node.js angularjs angular-routing route-provider

我使用 Angular 作为客户端,使用 Nodejs (Express) 作为服务器端来构建单页面应用程序。为了支持不同 View 的浏览器历史记录,我使用 $routeProvider。如果我不刷新浏览器,它效果很好。但每当我刷新浏览器时,我都会注意到 URL 发生了更改,这导致了问题,因为服务器上不存在该 URL 模式。以下是更多详细信息。

Angular js 路由器代码:

 $routeProvider.
                when('/categoryview', {
                    templateUrl: 'templates/partials/app/categoryview/CategoryView.html',
                    controller: 'ApplicationController'
                }).
                when('/:categoryId/themes', {
                    templateUrl: 'templates/partials/app/themeview/ThemeView.html',
                    controller: 'ThemeViewController'
                })
                .otherwise({redirectTo: '/categoryview'});

首次启动应用程序时浏览器中的 URL: http://localhost:3000/themelibrary#/categoryview

刷新时浏览器中的 URL: http://localhost:3000/categoryview#/categoryview

如果您注意到的话,您会发现根 URL "/themelibrary" 已更改为 "/categoryview",这会导致问题,因为不支持 "/categoryview"通过服务器。我也尝试了不同版本的 Angularjs 但没有成功。

如果需要更多代码来解释这个问题,请帮助并告诉我。

编辑:添加了 Nodejs 路由器详细信息 用户界面路由:

module.exports = function(app, passport) {
    // route for home page
    app.get('/', function(req, res) {      
        res.redirect('/login');
    });
    //Route for login to present the login page back to user
    app.get('/login', function(req, res) {       
        res.set({'content-type': 'text/html; charset=utf-8'})
        res.render('login.ejs', {message: req.flash('loginMessage')})
    });

 //Route to get the username and password and authenticate
    app.post('/authenticate', passport.authenticate('local-login', {
        successRedirect: '/themelibrary', // redirect to the secure themelibrary section
        failureRedirect: '/login', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));

     // route for default lending page
    app.get('/themelibrary', isLoggedIn, function(req, res) {       
        var url= require('url');
        console.log("themelibrary hash url >> " + url.hash);
        res.charset = 'utf8';
        res.set({'content-type': 'text/html; charset=utf-8'})
        res.render('index.ejs', {
            user: req.user
                    // get the user out of session and pass to template
        });
    });

// route middleware to make sure a user is logged in
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('/');
}

API 路由:

module.exports = function(app) {
    app.get('/users/:id', userService.getUserById);
    app.get('/users', userService.getAllUsers);
    app.post('/themes', themeService.addTheme);
    app.get('/themes/:id', themeService.getThemeById);
    app.put('/themes/:id', themeService.updateTheme);   
    app.delete('/themes/:id', themeService.deleteTheme);
    app.get('/themes', themeService.getThemes); 
    app.get('/resources/:code', languageResourceService.getLanguageResourceByCode); 
    app.get('/config', applicationConfigService.getApplicationConfig);  
    app.post('/keepalive', applicationConfigService.keepAlive); 
    app.get('/categories', categoryService.getAllCategories);
};

最佳答案

我需要查看您的快速路由规则才能给出完整答案,但由于根据 $routeProvider,themelibrary 不是有效路由,因此如果您浏览到此,您的 other 规则将被激活从您的应用程序中。

如果您在此 URL 刷新浏览器,$routeProvider 将被绕过,请求将直接发送到您的 Node.js 实例,express 将在其中处理路由。

至于哈希路由,这完全取决于您是否启用了 html5mode,正如 @david-spence 指出的那样。

编辑

终于在这一个上花了一分钱。如果您的 Angular 应用程序已加载(加载的唯一方法是通过 /themelibrary 路径),它将接管您的所有路由,因此通过应用程序进行的任何路由更改都将由ngRoute。也就是说,不会重新加载页面。因此,如果后端服务器受到对 /categoryview 的请求,则应用程序的其他部分正在通过 window.location.href 或其他方式请求完整页面重定向类似。

简而言之,您的路线没问题,应用程序的其他部分正在绕过您的路线并直接返回服务器(这是不应该的)。

关于node.js - URL 在浏览器刷新时发生更改($routeProvider 用于客户端路由),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022019/

相关文章:

node.js - 路由无法正常工作

javascript - 如何使用 NodeJs 请求 GET 模块发送 cookie?

node.js - Hack.chat 在我的公共(public) IP 上

node.js - 错误 HH604 : Error running JSON-RPC server: Must be authenticated! Hardhat Node.js Alchemy

javascript - angularjs x 可编辑控件在完成或取消后失去焦点

javascript - $routeChangeError 未在 $q.reject 上调用

angular - 如何使用 ActivatedRouteSnapshot 的 params 属性在组件中以不同方式填充数据

javascript - 使用 vtune 和 jitprofiling.h 支持编译 NodeJS

javascript - 面对动态数据的 ng-init 问题

javascript - 禁用 md-tab 中的 Md-(上一个/下一个)按钮