Ruby 使用RestClient和Sinatra发送和接收JSON

Ruby 使用RestClient和Sinatra发送和接收JSON,ruby,sinatra,rest-client,Ruby,Sinatra,Rest Client,我正试图通过RestClient ruby API向Sinatra应用程序发送JSON数据 在客户端(client.rb)(使用RestClient API) 服务器端(Sinatra) 我得到以下错误 /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/abstract_response.rb:53:in `return!': Resource Not Found (RestClient::ResourceNotFound)

我正试图通过RestClient ruby API向Sinatra应用程序发送JSON数据

在客户端(client.rb)(使用RestClient API)

服务器端(Sinatra)

我得到以下错误

/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数据。但是无论我怎么做,我都会得到上面的错误。我被这件事缠住了3个小时。请帮助

您的sinatra应用程序,与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}
试试这个:

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=>'我是一个值'}=>nil。您的数据根本不必在url中。您不需要/solve/:数据url。不能在url中发送帖子值 调试路由中接收到的内容的一个好方法是打印参数:

puts params

希望这有帮助

我没有重新启动sintara服务器。。这就是问题所在……)你的代码运行得很好
post '/solve' do 
  jdata = JSON.parse(params[:data])
  puts jdata
end
puts params