【问题标题】:Render json with status update 401使用状态更新 401 渲染 json
【发布时间】:2015-02-19 14:54:07
【问题描述】:

我正在尝试添加一个before_action 来检查用户并在没有用户的情况下将 json 返回到状态为 401 的角度应用程序。

功能很简单

 def authenticate_user
   if !logged_in
     render json: {:status => 401}
   end
 end

但是,这永远不会影响我的 httpInterceptor 并将 json 直接呈现到页面。我怎样才能让这个响应返回正确的标头,以便拦截器可以处理 401?

app.run(function($http, $cookies, $rootScope, $location) {
  $http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken;
  $http.defaults.headers.common['Content-Type'] = 'application/json';
});

app.factory('myHttpInterceptor', ['$cookies', '$location', '$window',
  function($cookies, $location, $window) {
    return {
      'request': function(config) {
        return config
      },
      'response': function(response) {
        if ($location.$$path !== '/' && !$cookies.csrftoken){
          $location.path('/');
        }
        return response
      }
    }
  }
]);

【问题讨论】:

    标签: ruby-on-rails json angularjs


    【解决方案1】:

    您是否将拦截器添加到 httpProvider 中?

    app.config(function($httpProvider) {
        $httpProvider.interceptors.push('myHttpInterceptor');
    })
    

    见:https://docs.angularjs.org/api/ng/service/$http

    【讨论】:

    • 如何请求应该以 401 响应的 API?使用 $http ?
    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2022-06-30
    • 2018-05-27
    相关资源
    最近更新 更多