简体   繁体   中英

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

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
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM