如何使用Rack接收JSON对象 [英] How to receive a JSON object with Rack
问题描述
我有一个非常简单的Ruby Rack服务器,例如:
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)
每当我使用JSON对象将POST HTTP请求发送到服务器时:
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 } }
我什么也没收到.我可以检测到收到的请求,但无法获取数据.在我的控制台上,puts req.inspect
的结果类似于:
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:
"{}"
我应该如何获取数据?
我试图用类似的方法来改变它:
I tried to change that with something like:
request = Rack::Request.new env
object = JSON.parse request.body
puts JSON.pretty_generate(object)
但是我收到以下警告:
!! Unexpected error while processing request: can't convert StringIO into String
推荐答案
env['rack.input'].gets
这对我有用.我发现使用curl或wget针对Rack(v1.4.1)服务器测试POST请求需要使用此代码作为获取请求正文的后备.狂放的POST请求(例如GitHub WebHooks)没有同样的问题.
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.
这篇关于如何使用Rack接收JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!