我正在编写一个应用程序,它运行Sinatra作为后台线程来提供API。
我为GET定义了一条工作正常的路线,但是当我尝试发布时,我一直看到它在同一个地方的WEBrick中失败了。错误是:
[2018-01-18 20:43:05] ERROR NoMethodError: undefined method `each' for nil:NilClass
/Users/atkinsb/.gem/ruby/2.4.0/gems/rack-2.0.3/lib/rack/handler/webrick.rb:90:in `service'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/httpserver.rb:140:in `service'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/httpserver.rb:96:in `run'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/server.rb:290:in `block in start_thread'
::1 - - [18/Jan/2018:20:43:05 GMT] "POST /message HTTP/1.1" 500 320
- -> /message
我认为问题出在第86行:
status, headers, body = @app.call(env)
当我发帖时,这总是为所有三个变量返回nil。
post '/message' do
ApiServer::Base::SM.message(JSON.parse(request.body.read))
end
帖子正文:
{
"id": "1",
"sender": "localhost",
"action": "SYS_NORMAL_SHUTDOWN",
"payload": "",
"ack": "0",
"date_time": "2018-01-18 08:58:50 +0000"
}
我在邮递员中张贴了一个标题:
Content-Type application/json
我很难过。知道我做错了吗?
PS。我忘了提到json的身体在路线上被解析好了......
从帖子返回的身体也是:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Internal Server Error</TITLE>
</HEAD>
<BODY>
<H1>Internal Server Error</H1>
undefined method `each' for nil:NilClass
<HR>
<ADDRESS>
WEBrick/1.3.1 (Ruby/2.4.2/2017-09-14) at
localhost:4567
</ADDRESS>
</BODY>
</HTML>
答案 0 :(得分:2)
嗯,毕竟那样。似乎问题是我需要回复某种反应。
# Server API route '/message'
def message(params)
js = build_message(params['action'], params['payload'])
write_message_to_file(js)
'{ "status": "Message Received" }'
end