Search code examples
javascriptjsoncorsnagios

Using JSON Query with Nagios API


I am developing a dashboard for Nagios and I would like to use the JSON Query generator Nagios provides to get the data.

Here is my 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"); 
};

I am getting this error with Chrome debug console :

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.

I know it's related to Access Control Origin policy, so I add this header to my Apache server :

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

I use Postman to check my request is working, and it is, even if Postman has no Access Control Origin policy, I can check that the following header is present on the response :

Access-Control-Allow-Origin → *

I tried a lot of things, but I can't get rid of this error.

Thanks for your time


Solution

  • To configure the CORS policy on my Apache 2 server using Nagios, here are the lines I had to add:

    • In /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 ^(.*)$ $1 [R=200]
      
    • In /etc/apache2/sites-enabled/nagios.conf: I replaced the line Require valid-user with:

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