You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Faraday请求LibreNMS API返回登录重定向HTML而非JSON问题排查

Fix: Faraday request to LibreNMS API returns login redirect HTML

Hey, let's figure out why your Faraday call is getting redirected to the login page while curl works perfectly. The key difference I spot right away is the path you're using in each request:

  • Your curl command hits https://librenms.mydomain.nl/api/v0/ports/25008
  • But your Faraday code is requesting /ports/25008.json (which becomes https://librenms.mydomain.nl/api/v0/ports/25008.json)

LibreNMS's API endpoints don't expect the .json suffix—you've already configured Faraday to handle JSON responses with conn.response :json, and curl works fine without it. When you add .json, LibreNMS doesn't recognize that as a valid API route, so it treats it like a regular web request that requires authentication, hence the redirect to login.

Here's how to fix it:

  1. Remove the .json from your request path
    Update your call method to match the path you used in curl:

    def call()
      response = libre_connection.get "/ports/25008"
    end
    

    With your path_prefix = "/api/v0" already set, Faraday will build the correct URL: https://librenms.mydomain.nl/api/v0/ports/25008—exactly what worked with curl.

  2. Optional: Double-check redirect handling
    If you still run into issues, you can explicitly add Faraday's redirect middleware to ensure it follows any legitimate redirects (though this shouldn't be necessary here):

    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"
        # Add redirect middleware to follow up to 3 redirects
        conn.use FaradayMiddleware::FollowRedirects, limit: 3
        conn.adapter Faraday.default_adapter
      end
    end
    

    But the main culprit here is definitely the extra .json suffix, so start with that change first.

After making this adjustment, your Faraday request should return the same JSON response as your curl command. LibreNMS will recognize it as a valid API request with a valid token, so no more login redirects!

内容的提问来源于stack exchange,提问作者perkoei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:47:09