Ruby 将 Json 响应发送到 http post call



我目前有Ruby代码,可以从客户端获取http帖子。 它制作了另一个 http 帖子,我想根据帖子的响应发送 json 响应。 我该怎么做? 我正在尝试使用这篇文章中的答案:如何在 Rails 中发送简单的 json 响应?

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

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>'

我想通过以下快速代码获得响应:

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()

你可以改变

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,您可以在此处找到文档。

最新更新