我对nodejs非常陌生,想要将MQTT客户端收到的消息推送到服务器前端。我已经成功获得了一个 MQTT 侦听器,它将通过 console.log 将接收到的数据写入控制台,并且我还使用express 创建了一个简单的服务器,其中包含包含文本区域的 index.html 页面。
但是,由于我很新,我不知道如何将mqtt消息发送到前端。我尝试过使用测试 app.post ,它可以将 html 显示更改为自定义消息,但如果在 mqtt 客户端中调用,它不起作用。
现在我正在尝试将 mqtt 消息发送到 html 页面上的文本框。
服务器.js:
const express = require("express");
const app = express();
var port = process.env.PORT || 1337;
app.listen(port, () => {
console.log("Application started and Listening on port " + port);
});
app.use(express.static(__dirname));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/Views/index.html");
console.log(__dirname + "/index.html");
});
app.post("/", (req, res) => {
res.send("Thank you for subscribing");
});
////'use strict';
var mqtt = require('mqtt');
var client = mqtt.connect("mqtt://192.168.0.165", { port: 1883, clientId: "test1", username: "admin", password: "mypassword" });
client.on("connect", function () {
console.log("connected " + client.connected);
});
client.subscribe("KSPL/devices/me", { qos: 0 });
client.on("message", (topic, message) => {
const buff = Buffer.from(message, "utf-8");
const msg = buff.toString();
console.log(msg);
console.log(app);
app.post("/", (req, res) => {
res.send(msg);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../server.css" rel="stylesheet" />
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css">
<title>html form</title>
</head>
<body>
<div class="subscribe-container">
<form method="POST" style="display:flex;">
<textarea name="mytextarea" style="width:100%"></textarea>
</form>
</div>
</body>
</html>
简短的回答是,你不需要。
您正在尝试将异步协议 (MQTT) 映射到同步协议 (HTTP)。如果不详细了解这意味着什么,就很难做到。您还尝试将推送操作(MQTT 代理发送新消息)映射到拉取操作(Web 浏览器使用 HTTP GET/POST 请求请求页面更新)。
更好的解决方案是确保 MQTT 代理支持基于 WebSocket 的 MQTT,然后在网页中实际运行 JavaScript MQTT 客户端,以便它可以直接订阅主题,然后在消息传递时根据需要更新页面。
您可以在页面中使用 Paho 客户端或 MQTT.js 客户端。