2014-02-22 41 views
2

我在Rails API上运行Angular。为了验证我截取401个状态用:设计JSON API返回200而不是401因为重定向

.config(['$httpProvider', function($httpProvider){ 
    // Prevent rails from making new sessions each time 
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content'); 

    var interceptor = ['$location', '$rootScope', '$q', function($location, $rootScope, $q) { 
     function success(response) { 
     return response; 
     } 

     function error(response) { 
     if (response.status === 401) { 
      $rootScope.$broadcast('event:unauthorized'); 
      $location.path('/login'); 
      return response; 
     } 
     return $q.reject(response); 
     } 

     return function(promise) { 
     return promise.then(success, error); 
     }; 
    }]; 
    $httpProvider.responseInterceptors.push(interceptor); 
    }]) 

但因为重定向的拦截而无法触发显示的200

Started GET "/api/v1/stages" for 127.0.0.1 at 2014-02-23 04:38:12 +0530 
Processing by StagesController#index as HTML 
Completed 401 Unauthorized in 5ms 


Started GET "/api/v1/users/sign_in" for 127.0.0.1 at 2014-02-23 04:38:12 +0530 
Processing by Devise::SessionsController#new as HTML 
    Rendered /home/kartikluke/.rvm/gems/ruby-2.0.0-p247/gems/devise-3.2.2/app/views/devise/shared/_links.erb (4.3ms) 
    Rendered /home/kartikluke/.rvm/gems/ruby-2.0.0-p247/gems/devise-3.2.2/app/views/devise/sessions/new.html.erb within layouts/application (34.5ms) 
Completed 200 OK in 223ms (Views: 171.2ms | ActiveRecord: 5.8ms) 

状态如何使设计返回401 JSON错误?

回答

4

经过大量的搜索,我找到了一个解决方案。

我添加了一个自定义的应用程序的故障,制定:

class JsonFailureApp < Devise::FailureApp 
    def respond 
    self.status = 401 
    self.content_type = 'json' 
    self.response_body = '{"error" : "authentication error"}' 
    end 
end 

,并补充说,制定:

config.warden do |manager| 
    manager.failure_app = JsonFailureApp 
end 

现在重定向不叫和而不是401状态被注册。

相关问题