相关疑难解决方法(0)

如何使用Rack接收JSON对象

我有一个非常简单的Ruby Rack服务器,如:

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)
Run Code Online (Sandbox Code Playgroud)

每当我使用JSON对象向服务器发送POST HTTP请求时:

{ "session": {
"accountId": String,
"callId": String,
"from": Object,
"headers": Object,
"id": String,
"initialText": String,
"parameters": Object,
"timestamp": String,
"to": Object,
"userType": String } } 
Run Code Online (Sandbox Code Playgroud)

我一无所获.我可以检测到收到的请求但无法获取数据.在我的控制台上的结果puts req.inspect是这样的:

"{}"
Run Code Online (Sandbox Code Playgroud)

我该如何获取数据?

我试图通过以下方式改变它:

request  = Rack::Request.new env
object   = JSON.parse request.body
puts JSON.pretty_generate(object)
Run Code Online (Sandbox Code Playgroud)

但我收到以下警告:

!! Unexpected error while processing request: can't …
Run Code Online (Sandbox Code Playgroud)

ruby json rack ruby-on-rails sinatra

5
推荐指数
2
解决办法
4994
查看次数

标签 统计

json ×1

rack ×1

ruby ×1

ruby-on-rails ×1

sinatra ×1