2

我正在使用瘦来接收 HTTP POST 请求,我的服务器代码是这样的:

http_server = proc do |env|
  # Want to make response dependent on content
  response = "Hello World!"
  [200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end

设置断点,可以看到收到了content-type(json),以及内容长度,但是看不到实际的内容。如何从处理请求中检索内容?

4

1 回答 1

2

您需要使用对象的rack.input条目env。从机架规格

输入流是一个类似 IO 的对象,其中包含原始 HTTP POST 数据。适用时,其外部编码必须为“ASCII-8BIT”并且必须以二进制模式打开,以兼容 Ruby 1.9。输入流必须响应getseach和。readrewind

所以你可以这样调用read它:

http_server = proc do |env|

  json_string = env['rack.input'].read
  json_string.force_encoding 'utf-8' # since the body has ASCII-8BIT encoding,
                                     # but we know this is json, we can use
                                     # force_encoding to get the right encoding

  # parse json_string and do your stuff

  response = "Hello World!"
  [200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end
于 2013-08-15T15:40:43.153 回答