1

我有一个代码如下:

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        ports.forEach(function(port) {
            var temp = port.manufacturer;
            console.log(temp);
            res.send(temp);
        });
    });
});

可以看出,port.manufacturer值被保存到变量 temp 中,并且 temp 的结果内容显示在控制台上。

当我运行上面的代码时,我在控制台上得到了这样的东西:

Listening on port 3000...
Tinkerforge GmbH
GET /list 200 219ms - 16
Arduino (www.arduino.cc)
GET /favicon.ico 404 4ms 

但是当我调用 api 时http://localhost:3000/list

仅显示 Tinkerforge GnbH,而不显示 Arduino。

有什么我在这里想念的吗?

我必须将列表保存在数组中吗?

任何帮助将非常感激。

提前非常感谢。顺便说一句,我在 node.js 和 javascript 中都是初学者。

4

1 回答 1

2

这里的问题是.send,与 不同.write,只能调用一次。调用时,Express 将分析数据并检测正确的标头 (res.writeHead) 以在写入 (res.write) 到套接字之前发送,最后关闭连接 (res.close)。

解决方案是一次性使用.write或发送所有数据。

使用 .write

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        ports.forEach(function(port) {
            var temp = port.manufacturer;
            res.write(temp);
        });
        res.send();
    });
});

使用 .send

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        var manufacturers = [];
        ports.forEach(function (port) {
            manufacturers.push(port.manufacturer);
        });
        res.send(manufacturers.join(" "));
    });
});

我可能会使用类似的东西JSON.stringify(manufacturers)而不是 using .join,因为 JSON 很容易使用。

于 2013-01-02T15:12:19.367 回答