我在客户端使用 Angular,在服务器端使用 Nodejs (Express) 来构建单页应用程序。为了支持不同视图的浏览器历史记录,我使用了 $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 路由器详细信息 UI 路由:
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);
};