Node Res.write 发送多个对象: [英] Node Res.write send multiple objects:

查看:59
本文介绍了Node Res.write 发送多个对象:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,我收到错误:

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用于将字符串写入响应正文,接受的参数是 (chunk[, encoding][,callback]),但是对象不是字符串,并且您的最小值/最大值不是编码.

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.

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

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

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

这篇关于Node Res.write 发送多个对象:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆