的 我对client.on和subscribe的理解非常错误。我重建了整个代码,现在它正在运行。 强>
var topicTemp = "FromESPtoWeb/temp"; var topicDoor = "FromESPtoWeb/door"; var topicWindow = "FromESPtoWeb/window"; var topicMoisture = "FromESPtoWeb/moisture"; var topicMotion = "FromESPtoWeb/motion"; var content = { doorMsg: "Door Closed" , windowMsg: "Window Closed", tempMsg:"", moistureMsg:"", motionMsg: ""}; client.on('connect', function () { client.on('message', function (topic, message) { if(topic === topicTemp) { temp(message); } if(topic === topicDoor) { door(message); } if(topic === topicWindow) { window(message); } if(topic === topicMoisture) { moisture(message); } if(topic === topicMotion) { motion(message); } }); client.subscribe(topicTemp, function (err) { if (err) { alert("something went wrong on subscribe to message"); } }); client.subscribe(topicDoor, function (err) { if (err) { alert("something went wrong on subscribe to message"); } }); client.subscribe(topicWindow, function (err) { if (err) { alert("something went wrong on subscribe to message"); } }); client.subscribe(topicMoisture, function (err) { if (err) { alert("something went wrong on subscribe to message"); } }); client.subscribe(topicMotion, function (err) { if (err) { alert("something went wrong on subscribe to message"); } }); }); var temp = (message) => { console.log(message.toString()); content.tempMsg = message.toString(); } var door = (message) => { if (message == "Door Open") { console.log("Door open"); content.doorMsg = message; }else if (message == "Door Closed") { console.log("Door closed"); content.doorMsg = message; } } var window = (message) => { if (message == "Window Open") { console.log("window open"); content.windowMsg = message; }else if (message == "Window Closed") { console.log("window closed"); content.windowMsg = message; } } var moisture = (message) => { console.log(message.toString()); content.moistureMsg = message.toString(); } var motion = (message) => { console.log(message.toString()); content.motionMsg = message.toString(); } /* GET home page. */ router.get('/', function(req, res) { res.render('index', { content : content } ); });
使用请求对象!
router.get('/', function(req, res) { res.render('index', { content : req.content } ); });