您需要以某种方式将数据存储在服务器端,以使方法起作用。
实现某种存储消息的存储服务。您的客户端需要响应队列消息并将其推送到存储,您的api操作将从存储而不是从队列中检索它们。
const mqtt = require('mqtt');
const express = require('express');
const PORT = 8000;
const app = express();
const storageService = require("SOME KIND OF STORAGE SERVICE");
var client = mqtt.connect("mqtt://bac.com");
client.on('connect',() => {
console.log("Connected")
client.subscribe('/test')
});
client.on('message',(topic,message) => {
storageService.save(topic,message); //or this has to provide storage and enterpretation of the data comming in
});
app.get("/",(req,res) => {
res.send("ROOT");
});
app.get("/main",res) => {
res.send(storageService.getAll());
});
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`);
});
您还可以重新访问整个实现,并通过套接字或其他某种持久性连接将消息推送到前端。
,
我从类似的问题here中找到了解决方法。在服务器端,它将根据收到的消息发送数据。在客户端,这是每秒的ajax调用,用于在服务器端检索数据。
如链接中所述,这确实是一个错误的模式。但是,这将适合那些对MQTT服务进行更改有约束的人。
// Server.js
const mqtt = require('mqtt')
const express = require('express')
const PORT = 8000
const app = express()
var client = mqtt.connect("mqtt://bac.com")
var mqttMessage
client.on('connect',() => {
console.log("Connected")
client.subscribe('/test')
})
client.on('message',message) => {
console.log('Topic: ' + topic + '\nMessage: ' + message)
mqttMessage = message
})
app.get("/",res) => {
res.sendFile("__dirname + "/index.html");
});
app.get("/main",res) => {
if(mqttMessage)
res.send(mqttMessage);
else
res.status(404).send();
});
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`);
});
以及在index.html页面上:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function () {
setInterval(function () {
$.get('/main',function (res) {
$('#data').text(res);
});
},1000);
}
);
</script>
<p id="data"></p>
</body>
本文链接:https://www.f2er.com/3104336.html