我在尝试使用 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 + '/');
});
此方法自动将页面重定向到“测试”路由,因为它使用表单来处理发布请求。
然而,当我使用 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 Controller 之类的东西
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 模式,否则您需要一个用于 Angular 重定向的主题标签。
关于javascript - 使用 Node.js 和 Angular 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943350/