mad*_*bel 5 ruby api ruby-on-rails
我正在Rails应用程序中创建一个API,但我在编码方面遇到了一些麻烦,所以看起来如此.我实际上确实不确定实际的错误是什么.我编写了一个模块,其中包含两个类.其中一个用于获取域的DNS记录.当我通过它实例化类,并调用一个方法它工作得很好,但是当我在我的Rails应用程序中运行它时,我被抛出一个错误说"\x90" from ASCII-8BIT to UTF-8
这有点来自我的班级
#
# Class initializer to set instance variable with domain
#
def initialize(domain)
@domain = domain
end
#
# Generates hash to be used in other methods
# @returns a hash with usefull info and made ready for later input
#
def generate_hash
hash = {
'timestamp' => Time.now.to_i,
'credits_remaining' => 123,
'response' => {
'domain' => @domain,
'records' => {}
}
}
return hash
end
#
# Get A Records for a domain
# @returns JSON formatted hash
#
def get_a_records
data = self.generate_hash
Resolv::DNS.open do |dns|
ress = dns.getresources @domain, Resolv::DNS::Resource::IN::A
p = ress.map { |r| r.address }
data['response']['records']['a'] = p
end
return data.to_json
end
Run Code Online (Sandbox Code Playgroud)
从我的控制器:
require 'domainapi'
class CallsController < ApplicationController
def index
render json: {'status': 'OK'}
end
def dns
dns = DomainAPI::Dns.new(params[:domain])
response = dns.get_a_records
render json: response
end
end
Run Code Online (Sandbox Code Playgroud)
我班上的索引方法运行得很好.我这样查询我的apihttp://api.lvh.me:3000/v1/dns/a/stackoverflow.com
该lvh.me域名是我使用的,因此我可以在本地使用子域名.有人可以看到可能出现的错误,或者对我能做什么有建议吗?
更新
我发现尝试不同的域,会抛出不同的错误.google.com抛出:
"\xF2" from ASCII-8BIT to UTF-8
facebook.com抛出:
"\xAD" from ASCII-8BIT to UTF-8
rubyonrails.org thows:
"\xC0" from ASCII-8BIT to UTF-8
mad*_*bel -1
因此,经过几个小时的尝试找出问题所在后,我已经弄清楚了。
问题出在我尝试将哈希编码为 JSON 的部分。显然 Rails 或我的应用程序不理解该.to_json方法,因此我必须使用JSON.generate(data)此处描述的序列化:http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#module- JSON-标签-生成+JSON
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |