4

我正在尝试通过 RestClient ruby​​ API 将 JSON 数据发送到 Sinatra 应用程序。

在客户端(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 数据。但无论我尝试什么,我都会收到上述错误。我坚持了3个小时。请帮忙

4

2 回答 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}
于 2010-06-08T12:31:53.760 回答
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 网址。POST 值不会在 url 中发送 调试您在路由中收到的内容的一个好方法是打印参数:

puts params

希望这可以帮助!

于 2011-10-19T15:02:21.520 回答