【问题标题】:Ruby send Json response to http post callRuby 向 http post 调用发送 Json 响应
【发布时间】:2018-01-28 08:46:24
【问题描述】:

我目前有 Ruby 代码,它从客户端获取一个 http 帖子。它发布了另一个 http 帖子,我想根据帖子的响应发送一个 json 响应。我该怎么做呢?我正在尝试使用这篇文章的答案:How to send simple json response in Rails?

但是当我尝试编译时它给了我错误。

require 'sinatra'
require 'rest-client'
require 'sequel'
require 'pg'
require 'json/ext'

require 'net/http'
require 'json'

require 'monza'
require 'time'

post '/receiptValidation' do
  # Find devices with the corresponding reg_tokens
  base64ReceiptDataString = params[:base64ReceiptDataString]


  uri = URI("https://sandbox.itunes.apple.com") 
    Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 
    'https') do |http|
      response = http.post('/verifyReceipt', params_json)
      parsedJson = JSON.parse(response.body)

      # ***** send JSON response here *******
      respond_to do |format|
      # ... other formats here ...
        format.jsonr do
          render :json => { 
            :status => :ok, 
            :message => "Success!",
            :html => "...insert html..."
          }.to_json
        end        
      end
  end
end

这是我得到的错误:

2017-08-20 02:36:04 - NoMethodError - undefined method `respond_to' for #<Sinatra::Application:0x007f0dcb04ba70>
2017-08-20T02:36:04.949145+00:00 app[web.1]: Did you mean?  respond_to?:
2017-08-20T02:36:04.949146+00:00 app[web.1]:    firebasepushserver.rb:315:in `block in <main>'

我想在下面的 swift 代码中得到响应:

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            print("done")
        }
        task.resume()

【问题讨论】:

  • 错误信息是什么?
  • 2017-08-20 02:36:04 - NoMethodError -
    '
    中的未定义方法 respond_to' for #&lt;Sinatra::Application:0x007f0dcb04ba70&gt; 2017-08-20T02:36:04.949145+00:00 app[web.1]: Did you mean? respond_to?: 2017-08-20T02:36:04.949146+00:00 app[web.1]: firebasepushserver.rb:315:in block
  • 您的应用似乎是 Sinatra 应用而不是 Rails。考虑编辑标签并删除问题中的 ruby​​-on-rails 标签。
  • 是的,它是一个 sinatra 应用程序。我不知道这与rails不同。所以我需要找到如何使用 sinatra?
  • 它们是不同的 Web 框架,尽管它们都是用 Ruby 编写的。

标签: json ruby rest sinatra


【解决方案1】:

你可以改变

respond_to do |format|
  # ... other formats here ...
  format.jsonr do
    render :json => {
        :status => :ok,
        :message => "Success!",
        :html => "...insert html..."
    }.to_json
  end
end

  content_type :json
  {
      :status => :ok,
      :message => "Success!",
      :html => "...insert html..."
  }.to_json

它使用content_type,你可以找到文档here

【讨论】:

  • 我尝试将代码块替换为您提供的代码块,但响应为空白。文档说这段代码填充了响应,但实际发送响应的命令是什么?
  • @mjpablo23 只要您将代码添加到 sinatra 的 post 块中,此代码肯定会起作用。因为我在我的电脑上测试过。
  • 啊,我明白了。我有它在帖子块。我一直在快速响应: response = Optional( { URL: appname.herokuapp.com/receiptvalidation } { status code: 404, headers { Connection = "keep-alive";
  • 这是它在 heroku 上打印的内容:[20/Aug/2017:05:29:27 +0000] "POST /receiptvalidation HTTP/1.1" 404 18 0.0024
  • 哦,我解决了 404 问题。但现在回复还是空白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
相关资源
最近更新 更多