0

I am searching for an example on how to push metric to the pushgateway via ajax.

echo 'some_metric 42' | curl --user user:pass --data-binary @- https://example.com/metrics/job/author_monitoring/jobname/count_open

with curl it works perfect!

I don't know how to translate this in js/jquery. Maybe someone has an example

Here is what I got so far.

(function ($, $document) {
  "use strict";

  function textToBin(text) {
    return (
      Array
      .from(text)
      .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
      .map(bin => '0'.repeat(8 - bin.length) + bin)
      .join(' ')
    );
  }

  var username = "user";
  var password = "pass";
  var metric = 'some_metric 42';
  var binaryData = textToBin(metric);

  $.ajax({
    url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
    data: binaryData,
    type: 'POST',
    crossDomain: true,
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
    },
    success: function () {
      console.log("Success");
    },
    error: function () {
      console.log('Failed!');
    }
  });

})($, $(document));

here is the error:

text format parsing error in line 1: invalid metric name
Michael Doubez
  • 5,937
  • 25
  • 39
Tim Schwalbe
  • 1,588
  • 4
  • 19
  • 37
  • 1
    Well, for one thing, [CORS doesn't work like that](https://stackoverflow.com/questions/37527962/add-cors-header-to-an-http-request-using-ajax). But it's not clear from your question whether you're having a CORS issue or something else. In any case, remove the header. – T.J. Crowder Mar 07 '19 at 08:09
  • its not an cors error I guess, the pushgateway returns 400. `text format parsing error in line 1: invalid metric name` – Tim Schwalbe Mar 07 '19 at 08:16

1 Answers1

0

okay I got it.

There is an easy solution, import is the \n at the end of the string.

(function ($, $document) {
  "use strict";
  var username = "user";
  var password = "pass";
  var metric = 'some_metric 42\n';

  $.ajax({
    url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
    data: metric,
    type: 'POST',
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
      xhr.setRequestHeader("Content-Type", "text/plain");
    },
    success: function () {
      console.log("Success");
    },
    error: function () {
      console.log('Failed!');
    }
  });
})($, $(document));
Tim Schwalbe
  • 1,588
  • 4
  • 19
  • 37