我正在尝试将响应中的多个对象作为 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/