客戶端是 esp32cam(camera module) 它每 3 秒向 app.js 發送一次影像
應用程式.js
client.on("message", async(topic, message)=>{ // {"LED" : "ON"} or {"MOTER" : "ON"}
if(topic == "JPG")
{
var obj = message.toString();
app.get("/img", function(req,res,next){
res.set("content-Type", "text/json");
//res.send(JSON.stringify({data : obj}));
res.json({
data: obj || "no image yet"
});
console.log(obj);//number 1
});
console.log(obj);//number 2
}
}
數字 1 是每 3 秒列印一次相同的資料
數字 2 是每 3 秒列印一次不同的資料
number1如何每次列印不同的資料?
html
$(function() {
timer = setInterval( function () {
console.log("timer")
$.ajax({
url: "http://ip:3000/img",
type: "get",
context : this,
cache : false,
error : function(request,status,error){
console.log("code:" request.status "\n" "message:" request.responseText "\n" "error:" error);
},
success:function(obj){
$("#imguri").html('<img src="' obj.data '">');
$("#imguri").attr("src", obj.data);
console.log("mqtt in " obj.data);
// console.log("TEST");
}
});
}, 3000);
});
我的問題


uj5u.com熱心網友回復:
這是因為您正在堆疊多個app.get("/img",...)路由(每個傳入訊息一個)。
只有第一個會被呼叫,所以 HTTP 客戶端總是會得到第一個影像。
您應該讓 MQTT 客戶端回呼將新影像存盤在全域變數中,然后讓/img路由的一個實體回傳該全域變數。
var img;
client.on("message", async(topic, message)=>{ // {"LED" : "ON"} or {"MOTER" : "ON"}
if(topic == "JPG")
{
var obj = message.toString();
img = obj
}
}
app.get("/img", function(req,res,next){
res.set("content-Type", "text/json");
res.json({
data: img || "no image yet"
});
console.log(obj);//number 1
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490667.html
標籤:javascript 节点.js MQTT
