在 Nagios API 中使用 JSON 查询

Using JSON Query with Nagios API

我正在为 Nagios 开发一个仪表板,我想使用 Nagios 提供的 JSON 查询生成器来获取数据。

这是我的JavaScript:

    window.onload = function(){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET","http://localhost/nagios/cgi-bin/statusjson.cgi?query=host&hostname=belge",true);
    Httpreq.setRequestHeader("Authorization", "Basic " + btoa("nagiosadmin:nagiosadmin"));
    Httpreq.send(null);
    var object = Httpreq.responseText;
    console.log(object); 
    button.textContent = "Yay";
    console.log("Success"); 
};

我在使用 Chrome 调试控制台时遇到此错误:

index.html:1 XMLHttpRequest cannot load http://localhost/nagios/cgi-bin/statusjson.cgi?query=host&hostname=belge. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.

我知道它与访问控制源策略有关,所以我将此 header 添加到我的 Apache 服务器:

Header set Access-Control-Allow-Origin "*"

我使用 Postman 检查我的请求是否有效,即使 Postman 没有访问控制源策略,我也可以检查响应中是否存在以下 header :

Access-Control-Allow-Origin → *

我尝试了很多东西,但我无法摆脱这个错误。

感谢您的宝贵时间

要使用 Nagios 在我的 Apache 2 服务器上配置 CORS 策略,以下是我必须添加的行:

  • /etc/apache2/apache2.conf:

    Header always set Access-Control-Allow-Origin "\*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Max-Age "1000"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$  [R=200]
    
  • /etc/apache2/sites-enabled/nagios.conf 中:我将行 Require valid-user 替换为:

    <LimitExcept OPTIONS>
      Require valid-user
    </LimitExcept>