Search code examples
node.jsnet-snmp

Nodejs /Net-SNMP :Error send snmp-walk response to client


I want create project for monitoring server by snmp. i use net-snmp component and express.i have error "Cannot set headers after they are sent to the client" when i want send response snmp walk to client.

I write the code.

var snmp = require('net-snmp');
var express = require('express');
app.on('/api/snmp/', (req, res) => {
  const session = new snmp.createSession(req.query.IP, req.query.Community);
  session.walk(
    '1.3.6.1',
    20,
    function(varbinds) {
     let msg = [];
      for (var i = 0; i < varbinds.length; i++) {
        if (snmp.isVarbindError(varbinds[i])) {
          console.log('error1');
        } else {
          console.log('send');
          msg.push({ message: varbinds[i].oid + '|' + varbinds[i].value });
        }
      }
      console.log(res.getHeaders());
      // res.setHeader('Content-Type', 'application/json');
      // res.send(msg);
      res.end(msg);
      // resolve(resultStr);
    },
    function(error) {
      console.log('error2');
      console.log(error.toString()); // show error in console: Cannot set headers after they are sent to the client
    }
  );
});

Solution

  • I can find solution when I convert type of "msg" variable to string that is worked. but i dont know why this have problem object type.