我很难理解 Angular.js 路由的行为
这是我的代码
我的 app.js:
'use strict';
var app = angular.module('myApp', []).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/game/room', {templateUrl: 'roomGame', controller: roomCtrl});
$routeProvider.otherwise({redirectTo: '/game/room'});
$locationProvider.html5Mode(true);
}]);
index.js 我在其中定义路由服务器端:
app.get('/game', function (req, res)
{
console.log("we are in /game");
res.render("game/index", {
user: req.session
});
});
app.get('/game/roomGame', function (req, res)
{
console.log("we are in /game/roomGame");
res.render("game/roomGame";
});
index.jade:
div(ng-controller="indexCtrl")
a(href='/') Quitter
div(ng-view)
还有另一个文件:roomGame.jade 但向您展示源代码并不重要。
现在我打开浏览器并输入:localhost:3000/game。
正如预期的那样,我被重定向到 localhost:3000/game/room,它显示了预期的 View 。
但是当我输入:localhost:3000/game/room 或 localhost:3000/game/foo 它显示“无法获取/game/xxx”
我想被重定向到/game,然后再到/game/room。怎么可能?
最佳答案
当您看到预期的 View 时,您是否被重定向到 http://localhost:3000/#/game/room
?请注意 #
。
当你输入 http://localhost:3000/game/room
时,这会访问 express 服务器,而不是你的 Angular 应用程序,试图匹配 /game/room
,因此您看到的消息。
一个想法是在你的服务器上这样做:
app.get('/game/:what', function (req, res) {
res.redirect('/#/game/' + req.params.what);
});
或更有可能:
app.get('/game/*', function (req, res) {
res.redirect('/#/game');
});
这会将事物从 express 重定向到 Angular 可以处理它们的地方。
关于javascript - Angular.js - 重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133785/