【问题标题】:Error on a Sinatra's middlewareSinatra 的中间件出错
【发布时间】:2012-09-13 01:29:06
【问题描述】:

在我的 Sinatra 应用程序中,我创建了以下中间件,以确保传入的请求在查询字符串中包含参数“token”

class CheckMandatoryParams
  def initialize(app)
    @app = app
  end
  def call(env)
    # Get token from query string
    h = Hash[*env["QUERY_STRING"].split('&').map {|s| s.split('=')}.flatten]
    token = h["token"]

    # Do not authorize request unless both parameters are not null
    if token.nil? then
      Log.instance.error("CheckMandatoryParams - token not provided")
      [401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, ["Unauthorized"]]
    else
      Log.instance.debug("CheckMandatoryParams - token provided")
      @app.call(env)
    end
  end
end

在参数存在的情况下,下一个应用是调用,一切正常。
如果参数不在查询字符串中,则不会发送响应,我会收到一个巨大的 html 文件,指示在 ' [401, {"Content-Type" => "text/plain", "Content -Length" => body.length.to_s}, ["Unauthorized"]]' 但我不知道出了什么问题。

有什么想法吗?

更新

这样效果更好:)

body = "Unauthorized"
[401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, [body]]

我没有设法使用以下代码检索参数:

request = Rack::Request.new(env)
token = request.params["token"]

【问题讨论】:

  • 我很想看看你从 Rack::Request 代码中得到了什么错误。这是我经常看到在 Sinatra 中访问参数的一种方式,而无需使用您自己的代码解析查询字符串。

标签: ruby sinatra rack middleware


【解决方案1】:

看起来“body”变量可能未定义。重写代码的一种可能方法如下:

class CheckMandatoryParams

  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    token = request.params["token"]
    if token.nil?
      [401, {"Content-Type" => "text/plain", "Content-Length" => request.body.length.to_s}, ["Unauthorized"]]
    else
      @app.call(env)
    end
  end

end

【讨论】:

  • 谢谢,您指出了正确的事情。我更新了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多