我目前拥有从客户端获取http帖子的Ruby代码。它创建了另一个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>'
我希望在以下快速代码中获得响应:
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()
答案 0 :(得分: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。