用Node.js和angular重定向



我在尝试使用Node.js, Express和angular重定向POST请求时遇到了麻烦。我知道有一种使用表单的标准方法,如下所示:

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 + '/');
});

该方法自动将页面重定向到"test"路由,因为它使用表单来处理post请求。

然而,当我使用angular方法时,页面不会自动重定向。我该怎么做呢?

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内部保持重定向,因为Angular是打算在自己的模块中保持客户端。就像我在评论中说的,你可以从服务器发送一个状态码,指示客户端进行重定向。

例如,将express端点更改为

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; 
    });
  }
}]);

这样就可以在服务器端代码中指定重定向地址。

编辑:此外,我认为你需要一个标签你的重定向在角,除非你有HTML5模式启用。

由node.js服务器创建的路由是实际的路由,而AngularJS的路由是基于哈希(#)标签,如-

node.js中的路由 -

app.get('/myroute')会像- http://localhost:8000/myroute

AngularJS中的路由 -

'/myangroute'会像- http://localhost:8000/#/myangroute

所以回到你的问题,$http.post('/redirect');不是重定向你,而是将数据发布到'/redirect'路由(在服务器端定义)。重定向使用angularjs的$location服务

最新更新