Angular.js – redirect不工作
我理解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,但是向您展示源代码并不重要。
现在我打开我的浏览器并input:localhost:3000 / game。
正如所料,我被redirect到本地主机:3000 /游戏/房间,它显示了我的预期的看法。
但是当我input:localhost:3000 /游戏/房间或本地主机:3000 /游戏/富它显示我“不能GET /游戏/ xxx”
我想被redirect到/游戏,然后到/游戏/房间。 怎么可能?
当你看到预期的视图,你是被redirect到http://localhost:3000/#/game/room
? 注意#
。
当你inputhttp://localhost:3000/game/room
,这会打击快递服务器,而不是你的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'); });
这将把事情从快递转到Angular可以处理的地方。