我正在使用Faraday gem从LibreNMS API请求一些数据。但是,当我显示响应正文时,我得到了一些HTML代码,它们看起来像是指向libreNMS登录名的重定向页面。
我有以下代码(BaseService类):
def libre_connection
Faraday.new(url: 'https://librenms.mydomain.nl') do |conn|
conn.path_prefix = "/api/v0"
conn.response :json, :content_type => /\bjson$/, :parser_options => { :symbolize_names => true }
conn.headers['X-Auth-Token'] = Rails.application.credentials[:libre][:key]
conn.headers["Content-Type"] = "application/json"
conn.adapter Faraday.default_adapter
end
然后是在扩展BaseService的类中的此内容
def call()
response = libre_connection.get "/ports/25008.json"
end
由于某种原因,给出以下响应:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0;url=https://librenms.mydomain.nl/login" /> <title>Redirecting to https://librenms.mydomain.nl/login</title> </head> <body> Redirecting to <a href="https://librenms.mydomain.nl/login">https://librenms.mydomain.nl/login</a>. </body> </html>
我知道令牌有效,因为当我执行以下curl命令时,我得到了我期望的JSON响应
curl -H 'X-Auth-Token: MYAPITOKEN' https://librenms.mydomain.nl/api/v0/ports/25008
任何人都知道我在做什么错吗?
您正在尝试通过HTTPS连接。对于本地开发,您可以尝试:
def libre_connection
Faraday.new(url: 'https://librenms.mydomain.nl') do |conn|
conn.ssl.verify = false # DONT DO THIS IN PRODUCTION
conn.path_prefix = "/api/v0"
conn.response :json, :content_type => /\bjson$/, :parser_options => { :symbolize_names => true }
conn.headers['X-Auth-Token'] = Rails.application.credentials[:libre][:key]
conn.headers["Content-Type"] = "application/json"
conn.adapter Faraday.default_adapter
end
end
对于生产,请参阅https://github.com/lostisland/faraday/wiki/Setting-up-SSL-certificates以了解如何正确配置SSL。