我有一个侦听两个端口的Node.JS服务器。标准HTTP位于端口3000上,它提供了两个路由的API:/getInfo
和/sendCommand
。我在3001上有另一个侦听器,用于连接设备的特定协议。目标是从Web界面执行API调用并将其发送到设备以接收输出。类似的东西:
GET localhost:3000/getInfo
server sends command to the device connected on localhost:3001
server receives some output
server responses to the request
由于Node.JS请求和响应与其他服务器异步,代码应该如何?
设备服务器:
var raspberryList = [];
function sendCommand(name, command) {
for (var i = 0; i < raspberryList.length; i++) {
if (!raspberryList[i].name.localeCompare(name)) {
raspberryList[i].write(command);
}
}
}
var server = net.createServer(function(socket) {
socket.name = socket.remoteAddress;
console.log(socket.name + " joined.";
raspberryList.push(socket);
socket.on('data', function(data) {
// TODO: Data received here should be displayed into the web interface
console.log(socket.name + " > " + data);
});
socket.on('end', function() {
raspberryList.splice(raspberryList.indexOf(socket), 1);
console.log(socket.name + " left.");
});
});
Node.JS API路线:
app.post('/getInfo', function(req, res) {
// TODO: send the command somehow and get the output
// Send the response
res.send(response);
});
答案 0 :(得分:0)
如果您在端口3001上使用HTTP,则可以尝试使用request。
var request = require('request');
app.post('/getInfo', function(req, res) {
request('http://localhost:3000/endpoint', function (error, response, body) {
if (error) throw error;
res.send(body);
});
});