好的,我试着遵循Spark文档,我想在我的单页面应用程序中执行简单的重定向。我的代码如下所示:
post("/users/login", (req, res) -> {
ObjectMapper mapper = new ObjectMapper();
User creation = mapper.readValue(req.body(), User.class);
User user = userService.getUser(creation.getLogin());
if (user.getPassword().equals(creation.getPassword())) {
req.session().attribute("userid", creation.getLogin());
System.out.println("OK");
res.status(201);
res.redirect("/index.html");
return "";
}
System.out.println("BAD");
return null;
} , json());基本上,我有三个静态html文件: registration.html、login.html和index.html。我读了一些关于staticFileLocation的东西,所以我在main函数的开头添加了以下几行代码:
staticFileLocation("/public");当我输入正确的登录名和密码时,我在Chrome的网络视图中发现,我向http://localhost:4567/index.html发出了状态为200的GET请求。但是,浏览器什么也不做,也不会将我重定向到该页面。你能告诉我我哪里做错了吗?
编辑:以下是处理客户端登录的javascript代码:
app.controller('LoginUserCtrl', function($scope, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/users/login',
data : $scope.loginUser,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function() {
console.log("User logged successfully");
console.log($scope.loginUser);
}).error(function() {
console.log("Unknown error while logging user");
});
};
});发布于 2016-01-26 16:30:01
错误之处在于,您正在重定向到post端点中的HTML页面,该页面应该返回Json数据。如果身份验证成功或失败,您必须返回单个json,如{"auth": "OK"}或{"auth": "NOK"},并根据它的信息决定从Javascript重定向到哪里。
发布于 2016-09-07 14:28:34
这是因为res.redirect会向浏览器发送一个重定向http报头(HTTP status值301、302、303和307),
但浏览器只能在get中重定向,不能在post、put或delete (在chrome中测试)中工作。请注意,浏览器发送了一个重定向请求,但页面并未更改...)。
请参见:
http://www.alanflavell.org.uk/www/post-redirect.html
https://stackoverflow.com/questions/34992607
复制相似问题