【问题标题】:Rails ApplicationController throwing not found for path找不到路径的 Rails ApplicationController 抛出
【发布时间】:2020-05-23 11:32:26
【问题描述】:

我在 routes.rb 中有以下内容:

Rails.application.routes.draw do
  resources :users, param: :email
  post '/auth/login', to: 'authentication#login'
  get '/*a', to: 'application#not_found'
  get '/attendance/in', to: 'attendances#in'
  get '/attendance/out', to: 'attendances#out'
  get '/user/get_attendance_status', to: 'users#get_attendance_status'
end

现在,例如,在我的users_controller.rb 中,我有以下操作:

before_action :authorize_request

def get_attendance_status
  render json: { at_work: @current_user.at_work }, status: :ok
end

:authorize_requestapplication_controller.rb中定义如下:

class ApplicationController < ActionController::API
    def not_found
        render json: { error: 'not_found' }
    end

    def authorize_request
        header = request.headers['Authorization']
        header = header.split(' ').last if header
        begin
            @decoded = JsonWebToken.decode(header)
            @current_user = User.find(@decoded[:user_id])
            rescue ActiveRecord::RecordNotFound => e
                render json: { errors: e.message }, status: :unauthorized
            rescue JWT::DecodeError => e
                render json: { errors: e.message }, status: :unauthorized
        end
    end
end

现在当我通过 Postman 向本地服务器提交请求时,出现以下错误:

Started GET "/user/get_attendance_status" for 58.177.56.127 at 2020-05-23 19:12:49 +0800
Processing by ApplicationController#not_found as HTML
  Parameters: {"a"=>"user/get_attendance_status"}
Completed 200 OK in 2ms (Views: 1.1ms | ActiveRecord: 0.0ms | Allocations: 93)


Started GET "/attendance/in" for 58.177.56.127 at 2020-05-23 19:13:14 +0800
Processing by ApplicationController#not_found as HTML
  Parameters: {"a"=>"attendance/in"}
Completed 200 OK in 1ms (Views: 0.3ms | ActiveRecord: 0.0ms | Allocations: 91)

如您所见,application_controller#not_found 被触发,但为什么呢?我不确定为什么会这样。任何见解将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    路由按照出现的顺序匹配,所以是的,你的 a* 路由应该放在最后。问题是你为什么需要这条路线?如果路由不存在,Rails 会自动返回 404。

    【讨论】:

    • 它返回一个 json
    【解决方案2】:

    我不得不将 get '/*a', to: 'application#not_found' 路由移到底部,所以我的 routes.rb 现在看起来像这样:

    Rails.application.routes.draw do
      resources :users, param: :email
      post '/auth/login', to: 'authentication#login'
      get '/attendance/in', to: 'attendances#in'
      get '/attendance/out', to: 'attendances#out'
      get '/user/get_attendance_status', to: 'users#get_attendance_status'
      get '/*a', to: 'application#not_found'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多