![](/img/trans.png)
[英]How to send multiple responses from Node js using res.write, so that the data appears live in the client?
[英]Node Res.write send multiple objects:
我正在嘗試將響應中的多個對象作為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)
我究竟做錯了什么? 我不能只發送字符串,因為我必須發送對象。
res.write(formattedData);
此處格式化的數據是一個對象。 如錯誤消息所述,write需要一個字符串或Buffer對象,因此必須對其進行轉換。 通過這樣做: res.write(JSON.stringify(formattedData))
。 節點希望內容不是對象,因為它需要字符串來傳遞給服務器。 服務器只能理解res.write()的 Nodejs Docs Nodejs Doc Link中提到的純文本輸入,默認情況下,編碼為'utf-8'。 因此,當通過服務器發送對象時,服務器會丟棄該對象,並拋出預期的緩沖區塊或字符串數據錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.