【问题标题】:can't access env['api.endpoint'] in grape middleware无法访问葡萄中间件中的 env['api.endpoint']
【发布时间】:2015-05-12 07:28:46
【问题描述】:

这里使用 Grape 编写 API 函数。我想要限制 API(API 速率限制)。

lib/grape/extensions/grape_extension.rb

module Grape
  module Extension
    module ThrottleExtension
      def throttle(options={})
        route_setting :throttle, options
        options
      end
      Grape::API.extend self
    end
  end
end

lib/grape/middleware/throttle_middleware.rb

module Grape
  module Middleware
    class ThrottleMiddleware < Grape::Middleware::Base
      def before
        binding.pry
      end
    end
  end
end

lib/grape_throttle.rb

require 'grape'
require 'grape/extensions/throttle_extension'
module Grape
  module Middleware
    autoload :ThrottleMiddleware, 'grape/middleware/grape_middleware'
  end
end

最后,在config/application.rb

require File.expand_path('../../lib/grape_throttle', __FILE__)
config.middleware.use Grape::Middleware::ThrottleMiddleware

并且,当我使用rails s 运行并调用 api 时,binding.pry 已调用。

[1] pry(#<Grape::Middleware::ThrottleMiddleware>)> env['api.endpoint']
=> nil

我想知道如何在 Grape 中间件中访问 env['api.endpoint']?

【问题讨论】:

    标签: api grape


    【解决方案1】:

    你可以通过:: 访问 env

    endpoint = @env["api.endpoint"]

    我已经在一个非 Rails 应用程序中进行了尝试,并且成功了。 您可以在变量中获取 api 端点的所有详细信息。

    【讨论】:

      【解决方案2】:

      我知道这已经有几年的历史了,但是我们今天在生产中遇到了这个问题,这是因为标题中的“content-type”没有设置为“application/json”。检查您在请求中发送的内容。

      我一直无法弄清楚为什么,但我也能够在Grape::API 中注释掉我们的use :&lt;middleware_name&gt;,并且我立即从grapes 中间件获得了"error": "The requested content-type 'text/plain' is not supported."

      【讨论】:

        猜你喜欢
        • 2014-12-06
        • 1970-01-01
        • 2015-06-13
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        相关资源
        最近更新 更多