如何在node.js中重新发送var到frontend,而无需重新加载,重定向或再次呈现这样的页面。我创建了一个聊天,我不想在有人发送消息后重新加载页面...是用QnA Microsoft制作的机器人。
res.render('mainpage',{frontend_var:backend_var});
前端
<div class="direct-chat-messages">
<%
for(var i = 0; i < imax;i+=2){
%>
<div class="direct-chat-msg doted-border">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">You</span>
</div>
<div class="direct-chat-text ">
<%=message[i+1]%>
</div>
</div>
<div class="direct-chat-msg ">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">BOT</span>
</div>
<img alt="message user image" src="http://www.pvhc.net/img27/awbgpcfkuwxixldjoown.png" class="direct-chat-img">
<div class="direct-chat-text ">
<%=message[i]%>
</div>
</div>
<%
}
%>
</div>
</div>
<form method="post" enctype="multipart/form-data" action="/users/send">
<div class="popup-messages-footer">
<input type="text" id="status_message" placeholder=" Type a message..." rows="10" cols="40" name="message">
<span class="input-group-btn right"><a class="waves-effect waves-light btn-small" > <input type="submit" value="Send"></a></span>
</div>
</form>
</div>
后端
app.post('/send',upload.any(),function (req,res,next) {
const translated = JSON.stringify({"question": req.body.message});
const extServerOptionsPost = {
host: 'westus.api.cognitive.microsoft.com',
path: 'https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases//generateAnswer',
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': '',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(translated)
}
};
const reqPost = http.request(extServerOptionsPost, function (bot) {
bot.on('data', function (data) {
process.stdout.write("done"); // primul console.log
imax++;
message[imax] = JSON.parse(data).answers[0].answer;
imax++;
message[imax] = req.body.message;
res.render('Bot', {message:message , imax:imax});
});
});
reqPost.write(translated);
});
答案 0 :(得分:0)
将此添加到您的nodeJS:它将作为后端钩子,前端(远处)可以保持联系。
//Given chatObject is a variable you want to send to the client:
app.get("/updateChats", function(req,res)
{
res.send(JSON.stringify(chatObject));
//Serializes the chatObject into a string
}
在客户端,您需要编写一些JSON同步内容:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// if it worked, parse that string, make it back into an object
var chatObject = JSON.parse(this.responseText);
console.log(chatObject)//do with it as you please :)
}
};
xmlhttp.open("GET", "/updateChats", true);
xmlhttp.send();
考虑setInterval
在前端设置同步代码以继续提取/刷新聊天消息