1

我正在使用 Faraday gem 从 LibreNMS API 请求一些数据。但是当我显示响应正文时,我会得到一些看起来像 libreNMS 登录的重定向页面的 HTML 代码。

我有以下代码(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

有人知道我做错了什么吗?

4

2 回答 2

0

您正在尝试通过 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。

于 2019-11-29T21:26:37.163 回答
0

谢谢大佬们的回复,我知道了。问题出在扩展 BaseService 的类中,这就是现在的样子:

class LibrenmsApi::ConnectionsService < LibrenmsApi::BaseService
def call()
    response = libre_connection.get "ports/25008"
end
end

注意“ports/25008”部分。我删除了开头的“/”并修复了它。

于 2019-12-04T11:31:22.467 回答