How to receive a JSON object with Rack

…衆ロ難τιáo~ 提交于 2019-11-30 15:45:59

问题


I have a very simple Ruby Rack server, like:

app = Proc.new do |env| 
  req = Rack::Request.new(env).params
  p req.inspect 
  [200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end 

Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)

Whenever I send a POST HTTP request to the server with an JSON object:

{ "session": {
"accountId": String,
"callId": String,
"from": Object,
"headers": Object,
"id": String,
"initialText": String,
"parameters": Object,
"timestamp": String,
"to": Object,
"userType": String } } 

I receive nothing. I can detect the request received but can't get the data. The results at my console for puts req.inspect is something like:

"{}"

How am I supposed to get the data?

I tried to change that with something like:

request  = Rack::Request.new env
object   = JSON.parse request.body
puts JSON.pretty_generate(object)

But I'm getting the following warning:

!! Unexpected error while processing request: can't convert StringIO into String

回答1:


env['rack.input'].gets

This worked for me. I found that using curl or wget to test POST requests against a Rack (v1.4.1) server required using this code as a fallback to get the request body. POST requests out in the wild (e.g. GitHub WebHooks) didn't have this same problem.




回答2:


It seems that I'm supposed to use something like:

msg = JSON.parse env['rack.input'].read 

Then just use params in the msg hash.

At least it worked for me this way.




回答3:


One more way to do that:

# ...
request  = Rack::Request.new env
object   = JSON.parse request.body.gets
# ...

See the documentation: www.rubydoc.info/gems/rack/Rack/Lint/InputWrapper



来源:https://stackoverflow.com/questions/9707034/how-to-receive-a-json-object-with-rack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!