node.jszabbixnode-fetchzabbix-api

Accessing zabbix API with node-fetch


I am trying to access Zabbix API from a Node.js app with the following code:

fetch(
  "http://localhost:8080/api_jsonrpc.php",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    data: {"jsonrpc":"2.0","method":"apiinfo.version","params":[],"id":1},
  }
)
  .then((data) => {
    return data.json();
  })
  .then((data)=>{
    console.log(data)
  })

But I get an error:

{
   jsonrpc: '2.0'
   error:{
      code:-32700,
      message: 'Parse error',
      data: 'Invalid JSON. An error occurred on the server while parsing the JSON text.'
   },
   id:null
}

However, when I use the following curl request, the API returns the correct value:

curl -i -X POST -H "Content-Type:application/json" -d '{"jsonrpc":"2.0","method":"apiinfo.version","params":[],"id":1}' http://localhost:8080/api_jsonrpc.php

It is probably some problem with my fetch request but I can't find it


Solution

  • The data argument seems wrong - it should be `body, and should be a string (or a few other options that aren't relevant here), not an object:

    fetch(
      "http://localhost:8080/api_jsonrpc.php",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: '{"jsonrpc":"2.0","method":"apiinfo.version","params":[],"id":1}' // Here!
      }
    )
    // The .then part was snipped for brevity's sake