使用RestClient和Sinatra发送和接收JSON

4
我将尝试使用RestClient Ruby API向Sinatra应用程序发送JSON数据。
在客户端(client.rb)中(使用RestClient API)。
response = RestClient.post 'http://localhost:4567/solve', jdata, :content_type => :json, :accept => :json

在服务器上(Sinatra)。
require "rubygems"
require "sinatra"


post '/solve/:data' do 

  jdata = params[:data]

  for_json = JSON.parse(jdata)

end

我收到以下错误提示。
/Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/abstract_response.rb:53:in `return!': Resource Not Found (RestClient::ResourceNotFound)
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:193:in `process_result'
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:142:in `transmit'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:543:in `start'
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:139:in `transmit'
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:56:in `execute'
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:31:in `execute'
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient.rb:72:in `post'
    from client.rb:52

我想要使用RestClient和Sinatra发送JSON数据并接收JSON数据返回,但是无论我尝试什么,都会出现上述错误。我被卡住了三个小时,请帮忙。
2个回答

14

你的sinatra应用程序与http://localhost:4567/solve URL不匹配,因此服务器返回404错误。

你需要按照以下示例更改你的sinatra应用程序:

require "rubygems"
require "sinatra"


post '/solve/?' do 
  jdata = params[:data]
  for_json = JSON.parse(jdata)
end
你的 RestClient 请求也存在问题。你需要定义 jdata 参数的名称。
response = RestClient.post 'http://localhost:4567/solve', {:data => jdata}, {:content_type => :json, :accept => :json}

我没有重新启动我的Sinatra服务器...这就是问题所在.. ;) 你的代码运行得很好。 - Anand

0

试试这个:

jdata = {:key => 'I am a value'}.to_json    
response = RestClient.post 'http://localhost:4567/solve', :data => jdata, :content_type => :json, :accept => :json

然后尝试这个:

post '/solve' do 
  jdata = JSON.parse(params[:data])
  puts jdata
end

我没有测试过,但也许你应该将json数据作为值而不是键发送。你的数据可能看起来像这样:{:key => 'I am a value'} => nil。你的数据不一定非要在url中。你不需要/solve/:data url。POST值不应该在url中发送。

调试路由接收到的内容的好方法是打印参数:

puts params

希望这能帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接