【问题标题】:Rails Grape API 'id is invalid' in request that requires no id在不需要 id 的请求中,Rails Grape API 'id is invalid'
【发布时间】:2015-12-28 17:04:38
【问题描述】:

我有一个受 Doorkeeper 保护的 Grape API,并且我有很多可以完美运行的方法。但是,有一种方法表现得很奇怪。 这是一个不需要参数的 GET 请求,运行它会引发以下错误:

Grape::Exceptions::ValidationErrors at /v1/discount_cards/all.json

id 无效

我的方法是这样的:

desc 'Get all the cards of current customer'
params {}
get 'all' do
  current_customer.discount_cards.to_json(include:
  {
    barcode: {
      include: :barcode_type
    }
  })
end

日志显示错误发生在logger.rb 文件的第 17 行,如下所示:

module API
  class Logger
    def initialize(app)
      @app = app
    end

    def call(env)
      payload = {
        remote_addr: env['REMOTE_ADDR'],
        request_method: env['REQUEST_METHOD'],
        request_path: env['PATH_INFO'],
        request_query: env['QUERY_STRING'],
        x_organization: env['HTTP_X_ORGANIZATION']
      }

      ActiveSupport::Notifications.instrument 'grape.request', payload do
        @app.call(env).tap do |response| # <-- logs say the error is here
          payload[:params] = env['api.endpoint'].params.to_hash
          payload[:params].delete('route_info')
          payload[:params].delete('format')
          payload[:response_status] = response[0]
        end
      end
    end
  end
end

我的主要base.rb 类如下所示:

module API
  class Dispatch < Grape::API
    mount API::V1::Base
  end

  Base = Rack::Builder.new do
    use API::Logger
    run API::Dispatch
  end
end

我真的不明白id 在说什么,而且,所有其他 api 方法都可以正常工作(post、get、put、delete)。

您能帮我解决这个问题吗?

【问题讨论】:

  • 您找到解决方案了吗?即使我面临同样的问题,我也无法理解它试图从错误消息中传达什么。

标签: ruby-on-rails api grape-api doorkeeper


【解决方案1】:

我最近也遇到了这个问题,结果对我来说是代码顺序问题。我找到了答案here

Grape 按顺序评估路由,因此对于 /:id 和 /nearby_missions 这两条路由,它首先匹配 /:id,使 id=nearby_missions。然后它会尝试将 near_missions 强制转换为 Integer,但失败了,你会得到缺少 id 的错误。

您可以通过向第一条路线添加要求来“解决”这个问题: /\d*/ (未测试),但您最好按照您希望它们被评估的顺序对它们进行排序,这是你做的。

您的问题中没有足够的信息让我确定这也是您的问题,但很可能是!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2016-02-14
    • 2022-06-20
    相关资源
    最近更新 更多