sli*_*801 5 javascript redirect node.js express angularjs
我在尝试使用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>
Run Code Online (Sandbox Code Playgroud)
test.ejs
<!DOCTYPE html>
<html>
<head>
<title>Redirect Example</title>
</head>
<body>
<p>YAY REDIRECTED</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
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 + '/');
});
Run Code Online (Sandbox Code Playgroud)
此方法自动将页面重定向到"测试"路由,因为它使用表单来处理发布请求.
但是,当我使用角度方法时,页面不会自动重定向.我该怎么做?
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>
Run Code Online (Sandbox Code Playgroud)
main.js
var app = angular.module('project', []);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.submit = function() {
$http.post('/redirect');
}
}]);
Run Code Online (Sandbox Code Playgroud)
尝试保持Angular中的重定向,因为Angular意味着在自己的模块中保持客户端.就像我在评论中所说,您可以从服务器发送状态代码,指示客户端进行重定向.
例如,将您的快速端点更改为类似的端点
app.post('/redirect', function(req, res){
res.status(300).send({ redirect:"/test"});
});
Run Code Online (Sandbox Code Playgroud)
和你的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;
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
这样,您可以在服务器端代码中指定重定向地址.
编辑:此外,我认为除非您启用了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服务。
| 归档时间: |
|
| 查看次数: |
8313 次 |
| 最近记录: |