【问题标题】:AngularJS $http ajax does not follow Location headerAngularJS $http ajax 不遵循 Location 标头
【发布时间】:2013-12-14 13:26:06
【问题描述】:

我正在使用 Spring Security 插件运行 Grails。在客户端,我正在运行AngularJS,我想从那里对用户进行身份验证。理想情况下,我想使用来自 Angular 的 $http 模块,但显然它不遵循服务器发送的 Location: 标头。

发生的情况是 Spring Security 返回一个 302 Moved temporarily,应该像 jQuery 一样自动查询/关注它。

下面的jQuery sn-p 工作正常,并根据Location: "http://agrarius.nl/login/ajaxSuccess" 响应标头创建一个新的GET 请求:

$.ajax({
    url: serverUri+'/j_spring_security_check?ajax=true', 
    data: data,
    method: 'POST'
})

AngularJS 方法似乎没有遵循任何东西,只是退出:

// Setup Config
var data = {
    j_username: $scope.user.email,
    j_password: $scope.user.password
}

var config = {
    method: 'POST', 
    url: serverUri+'/j_spring_security_check?ajax=true', 
    data: $.param(data),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},

};

// Dispatch HTTP Request
$http(config)
.success(function(data, status, headers, config) {
    if (data.status) {
        // successful login
        User.isLogged = true;
        User.username = data.username;
    }
    else {
        User.isLogged = false;
        User.username = '';
    }
    $scope.loggingIn = false;
})
.error(function(data, status, headers, config) {
    $scope.loggingIn = false;
    User.isLogged = false;
    User.username = '';

    if (status == 0) {
        // Request got cancelled
        console.log("Request got cancelled.");
        return;
    }
});

知道为什么会这样;以这种方式运行?而使用 jQuery 是否“安全”? :)

【问题讨论】:

  • 我最终使用了 jQuery ajax 函数,不知道为什么 AngularJS 出现故障。
  • 上次发表评论后整整 1 年,问题仍然存在。很高兴知道 jQuery 作为一种解决方法存在。

标签: jquery angularjs grails spring-security


【解决方案1】:

您可以尝试以下方法:

$http.post(serverUri+'/j_spring_security_check?ajax=true', $.param(data))
.then(function (response){
    var location = response.headers('Location');
    return $http.get(location);
})
.then(function (response) {
    if (response.data.status) 
    {
      // successful login
      User.isLogged = true;
      User.username = response.data.username;
    }
    else 
    {
      User.isLogged = false;
      User.username = '';
    }
    $scope.loggingIn = false;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2021-09-23
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多