client is esp32cam(camera module) It is send Image to app.js every 3seconds
app.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
}
}
number 1 is print same data every 3seconds
number 2 is print different data every 3seconds
how can number1 print different data each time??
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);
});
CodePudding user response:
This is because you are stacking multiple app.get("/img",...)
routes (one for every incoming message).
Only the first one will ever be called, so the HTTP client will always just get the very first image.
You should make the MQTT client callback store the new image in a global variable and then just have one instance of the /img
route return that global variable.
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
});