Reputation: 363
I am writing an app that runs Sinatra as a background thread to provide an API.
I defined a route for a GET that works ok but when I try post I keep seeing it fail in WEBrick at the same place. The error is:
[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
I think the problem is on line 86:
status, headers, body = @app.call(env)
This always returns nil for all three variables when I do the post.
post '/message' do
ApiServer::Base::SM.message(JSON.parse(request.body.read))
end
The post body:
{
"id": "1",
"sender": "localhost",
"action": "SYS_NORMAL_SHUTDOWN",
"payload": "",
"ack": "0",
"date_time": "2018-01-18 08:58:50 +0000"
}
I'm posting with a header in postman:
Content-Type application/json
I'm stumped by this. Any idea what I am doing wrong?
PS. I forgot to mention that the json body is parsed ok in the route...
Also the body returned from the post is:
<!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>
Upvotes: 0
Views: 282
Reputation: 363
Well, after all that. It seems that the problem was I needed to return some sort of response.
# Server API route '/message'
def message(params)
js = build_message(params['action'], params['payload'])
write_message_to_file(js)
'{ "status": "Message Received" }'
end
Upvotes: 2