javascript - Node Res.write发送多个对象:

标签 javascript node.js express request response

我正在尝试将响应中的多个对象作为 json 从一条路由发送回客户端。它是某种中间件,被调用,然后它在内部调用自己的另一个路由来获取数据并进行一些数据处理。这是代码:

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

但是,我收到错误:

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)

我做错了什么?我不能只发送字符串,因为我必须发送对象...

最佳答案

Write用于将字符串写入响应正文,接受的参数是(chunk[,encoding][,callback]),但是对象不是字符串,并且您的最小/最大值不是编码。

如前所述,您可以使用 JSON.stringify 将对象转换为 JSON 字符串,但是由于这是非常常见的行为,Express 提供了 send方法可以做到这一点。

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

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

关于javascript - Node Res.write发送多个对象:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223175/

相关文章:

node.js - 使用 Mocha 测试 Express : a promise-based test will not run by itself?

javascript - 如何将变量从 PHP 传递到外部 JS 文件?

node.js - 想要找到为给定的pdf文件生成缩略图的方法

javascript - d3 - 模拟 x Axis 的标签

node.js - 检查用户是否通过socket io收到消息

node.js - 如何在 Sequelize 中使用 and 运算符

node.js - 更新 Mongoose 中的嵌套数组

node.js - 如何销毁 session ?

javascript - 跳过 :first-child selector 上的隐藏元素

javascript - 如何使用 vue-chartjs 将图像添加到图表标签?