0

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...

2
  • formattedData isn't a String or Buffer. To send JSON with res.write, construct a single object first that contains all the data. Then call res.write(JSON.stringify(obj)); So you'll want something like res.write(JSON.stringify({ min: min, max: max, data: formattedData })); Commented Sep 7, 2018 at 13:09
  • thanks that worked pretty nice. Commented Sep 7, 2018 at 16:10

2 Answers 2

2

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this worked nicely with JSON.stringify or res.send, just had to create everything into a new object: {...} :)
0

res.write(formattedData); Here formatted data is a object . As the error message says, write expects a string or Buffer object, so you must convert it. by doing so : res.write(JSON.stringify(formattedData)) . The node expects the content to not to be a object because it needs string to pass on to the server. The server only understands plain text input as mentioned in Nodejs Docs Nodejs Doc Link for res.write() , and by default the encoding is 'utf-8' . so When sending a object through the server , the server discards it and throws an error of expected buffer chunks or string data.

1 Comment

its not a number, its an array of different objects.. [{..},{..},{..}..]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.