Search code examples
javascriptnode.jsexpressrequestresponse

Node Res.write send multiple objects:


I am trying to send multiple objects in the response as json back to client from one route. It is some kind of middleware, that gets called, and then it calls itself another route inside to get the data and do some data processing. Here is the code:

const axios = require('axios');
var datetime = require('node-datetime');

    function MiddlewareRoutes(router) {
        var MiddlewareController = require('../controllers/MiddlewareController')
        router.route('/Middleware/someotherLink/parametres').get(function(req,res,next) {

          console.log(req.params.id, req.params.startTime, req.params.endTime);
          url = `http://localhost:hidden/link/..`;
          url2 = "http://localhost:port+params..."

          axios.get(url) //, {responseType: 'json',}
          .then(response => {
            var formattedData = formatData(response.data);
            [max,min] = getMinMax(formattedData);
            res.write("max:",max);
            res.write("min:",min);
            res.write(formattedData);
            res.end();

          })
          .catch(error => {
            console.log(error);
          });
        })      
    }

However, I am getting the error:

TypeError: First argument must be a string or Buffer
    at write_ (_http_outgoing.js:642:11)
    at ServerResponse.write (_http_outgoing.js:617:10)
    at axios.get.then.response (C:\Users\U500405\Desktop\Backend\routes\MiddleWare.js:19:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

What am I doing wrong? I cannot just send strings, because I have to send objects...


Solution

  • Write is for writing strings to the response body, the parameters accepted are (chunk[, encoding][,callback]), however an object is not a string, and your min/max values are not encodings.

    As said before, you could use JSON.stringify to convert an object into a JSON string, however since this is pretty common behaviour Express provides a send method that can do exactly that.

    res.write(JSON.stringify({
        min, 
        max, 
        formattedData
    }));
    

    or

    res.send({
        min,
        max,
        formattedData
    });