redirectNode.js和angular度
我无法尝试使用Node.js,Express和angularredirectPOST请求。 我知道有一个使用forms的标准方式如下:
index.ejs
<!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <body> <p>INDEX PAGE</p> <form action="/redirect" method="post"> <button type="submit">CLICK</button> </form> </body> </html>
test.ejs
<!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <body> <p>YAY REDIRECTED</p> </body> </html>
app.js
var fs = require('fs'); var https = require('https'); var express = require('express'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var app = express(); app.set('view engine', 'ejs'); app.get('/', function(req, res) { res.render('index'); }); app.post('/redirect', function(req, res){ res.redirect('/test'); }); app.get('/test', function(req, res) { res.render('test'); }); var port = process.env.PORT || 1337; app.listen(port, function(){ console.log('http://localhost:' + port + '/'); });
此方法自动将页面redirect到“testing”路由,因为它使用表单来处理发布请求。
但是,当我使用angular度方法时,页面不会自动redirect。 我将如何做到这一点?
index.ejs
<!DOCTYPE html> <html ng-app="project"> <head> <title>Redirect Example</title> <script src="/javascripts/jquery/jquery.js"></script> <script src="/javascripts/angular/angular.js"></script> <script src="/javascripts/angular/angular-route.js"></script> <script src="/javascripts/main.js"></script> </head> <body ng-controller="MainController"> <button type="submit" ng-click="submit()">CLICK</button> </body> </html>
main.js
var app = angular.module('project', []); app.controller('MainController', ['$scope', '$http', function ($scope, $http) { $scope.submit = function() { $http.post('/redirect'); } }]);
尝试在Angular内部保留redirect,因为Angular意味着将客户端留在自己的模块中。 就像我在评论中所说的,你可以从服务器发送一个状态码,指示客户端做一个redirect。
例如,将您的快速端点更改为类似的东西
app.post('/redirect', function(req, res){ res.status(300).send({ redirect:"/test"}); });
和你的angular度控制器的东西
var app = angular.module('project', []); app.controller('MainController', ['$scope', '$http', '$window', function ($scope, $http, $window) { $scope.submit = function() { $http.post('/redirect').then(function(data, status){ $window.location.href = data.redirect; }); } }]);
这样您就可以从服务器端代码中指定redirect地址。
编辑:另外,我认为你需要一个hashtag的angular度redirect,除非你有HTML5模式启用。
由node.js服务器创build的路由是实际路由,而AngularJS路由基于哈希(#)标签,如 –
node.js中的路由 –
app.get('/ myroute')会像 – http:// localhost:8000 / myroute
AngularJS中的路线 –
'/ myangroute'将会像 – http:// localhost:8000 /#/ myangroute
所以回到你的问题, $http.post('/redirect');
不是redirect你,而是将数据发布到'/redirect'
路由(在服务器端定义)。 redirect使用angularjs $location
服务。