我想從串口讀取資料并在需要時從資料中獲取
這是我的代碼
const http = require('http');
const hostname = 'localhost';
const { SerialPort } = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
const { io } = require('socket.io');
let express = require('express')
const serialPort = new SerialPort({
path: 'COM4',
baudRate: 9600 ,
})
const parser = serialPort.pipe(new ReadlineParser({ delimiter: '\r\n' }))
let app = express();
var port = 8080;
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
app.get('/get_data', function(req, res) {
parser.on('data', function(data) {
res.json({'weight': data});
});
});
當我嘗試獲取資料時,我得到了 ERR_HTTP_HEADERS_SENT:在將標頭發送到客戶端后無法設定標頭我想要從 localhost:8080/get_data 請求的串行埠資料有人可以幫忙嗎?
uj5u.com熱心網友回復:
您的資料事件parser可能不止一次觸發,這意味著您將多次呼叫res.json。正如您在express api 檔案中看到的那樣,res.json設定content-type標頭...因此您只能在每個請求中呼叫它一次。因此錯誤。
我認為在這種情況下通常會做的是建立一個排隊系統。一個簡單的版本可以使用陣列來完成,盡管如果您在生產服務器中使用它,最好使用適當的訊息佇列系統(例如 rabbitMQ、kafka、AWS SQS 等)。
這是一個如何使用陣列的示例:
const queue = [];
parser.on('data', function(data) {
// push new data onto end of queue (array)
queue.push(data);
});
app.get('/get_data', function(req, res) {
if (req.params.getFullQueue === 1) {
// empty complete contents of current queue,
// sent to client as an array of { weight: x } objects
const data = queue.splice(0, queue.length)
.map(x => ({ weight: x }));
res.json(data);
} else {
// get oldest enqueued item, send it only
res.json({ weight: queue.shift() });
}
});
if/else中的旨在app.get說明這兩個選項,具體取決于您要使用的選項。在生產環境中,您可能希望實作分頁,或者甚至是 websocket 或 EventSource,以便在資料可用時推送資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447607.html
上一篇:兩個expressjs應用程式在不同的執行緒上運行?
下一篇:找不到路由模塊
