如何强制Angular在HTML5模式下向服务器发送请求?

我正在使用angular和nodejs来构build和web。 我在/homepath中加载Angular,其中/包含login和registry单。 这是我的angular度configuration:

 window.app.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider) { $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); $routeProvider. when('/profile', { templateUrl: '/views/account.html', }). when('/edit', { templateUrl: '/views/edit.html', }). when('/home', { templateUrl: 'views/index.html' }). when('/signout', { templateUrl: 'views/signout.html' //on this view i load a controller which submits a form to /signout }). otherwise({ redirectTo: '/home' }); } ]); 

在服务器端路由:

  app.get('/',function(){ res.render('index',{ user: req.user? req.user:'guest' }); }); app.post('/login',function(){ //if success redirect to /home //if fails redirect to / }); app.get('/auth/facebook', passport.authenticate('facebook', { scope: [ 'email', 'user_about_me', 'read_stream', 'publish_actions'], failureRedirect: '/' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), users.authCallback); app.get('/signout',function(){ //signing out the user here...and redirects to / }); app.get('/home',function(req,res){ res.render('users/home',{ user: req.user? req.user:'guest', message: req.flash('error') }) }); app.get('/profile',function(req,res){ res.render('users/home',{ user: req.user? req.user: 'guest', message: req.flash('error') }) }); app.get('/edit',function(req,res){ res.render('users/home',{ user: req.user? req.user:'guest', message: req.flash('error') }) }); 

我如何发送请求通过点击链接上的url/home/auth/facebook由于Angular路由,如果我点击Facebook身份validation它把我送到/home 。 angular度防止发送请求到服务器,它只是去url /home ,我试图通过replace/删除否则/home 。 结果是一样的,没有视图加载在那里。

从文档 :

在以下情况下,链接不会被重写。 相反,浏览器将执行整个页面重新加载到原始链接。

  • 包含目标元素的链接。 例如: <a href="/ext/link?a=b" target="_self">link</a>

  • 绝对链接到不同的域。 例如: <a href="http://angularjs.org/">link</a>

  • 以'/'开头的链接在定义基地址时会导致不同的基本path。 例如: <a href="/not-my-base/link">link</a>

所以,作为一个最简单的解决scheme,只需将target="_self"到您的链接。

如果您希望在一个位置更改路线configuration,而不是更改所有链接元素,则可以这样做:

 $routeProvider.when('/externalpath', { resolve: { redirect: ['$location', function($location) { window.location.replace($location.absUrl()); }] }}); 

这基本上调用内联函数,每当到达该路由的链接命中,该function只是redirect浏览器到目标位置(angular度之外)。 无论是为路由configuration模板还是控制器,“parsing”configuration都会被处理,“redirect”名称基本上只是一个虚拟名称 – 重要的是该函数被执行以获取其值(未使用在这种情况下)。

这也是有用的,例如你有一个/注销的url,需要到达服务器。 如果您希望服务器处理所有未configuration的path,则还可以使用otherwise()configuration,而不使用when()。