【发布时间】:2017-04-14 03:35:57
【问题描述】:
所以,下面是我的 server.js 文件中的代码 sn-p。运行时,我发送一个带有消息的 URL, res.end() 导致视图呈现一个空白页面。
当我注释掉 res.end() 命令时,视图会显示所有消息,但浏览器会一直等待服务器响应完成的信号。
我知道您可以使用 res.end() 并将数据放入括号中,以便由视图传输和呈现。
我期望发生的是,没有 args,它只会留下视图,但括号中的空 args 表现为一个空视图。
如何在不删除视图数据的情况下表明响应已完成?
server.js
var http = require('http'),
url = require('url'),
fs = require('fs');
var messages = ["testing"];
var clients = [];
http.createServer(function(req,res) {
var url_parts = url.parse(req.url);
console.log(url_parts);
if(url_parts.pathname == '/') {
// file serving
fs.readFile('./index.html', function(err, data) {
// console.log(data);
res.end(data);
});
} else if(url_parts.pathname.substr(0,5) == '/poll'){
//polling code
var count = url_parts.pathname.replace(/[^0-9]*/,'');
console.log(count);
if(messages.length > count){
res.end(JSON.stringify({
count: messages.length,
append: messages.slice(count).join("\n")+"\n"
}));
} else {
clients.push(res);
}
} else if(url_parts.pathname.substr(0, 5) == '/msg/') {
// message receiving
var msg = unescape(url_parts.pathname.substr(5));
messages.push(msg);
while(clients.length > 0) {
var client = clients.pop();
client.end(JSON.stringify({
count: messages.length,
append: msg+"\n"
}));
}
// res.end(); //if left in, this renders an empty page, if removed,
// client keeps waiting....
}
}).listen(8080, 'localhost');
console.log('server running!');
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
var counter = 0;
var poll = function() {
$.getJSON('/poll/'+counter, function(response) {
counter = response.count;
var elem = $('#output');
elem.text(elem.text() + response.append);
//elem.text(counter);
poll();
});
}
poll();
</script>
</head>
<body>
<textarea id="output" style="width: 90%; height: 90%;">
</textarea>
</body>
</html>
我查看了文档,但没有看到任何关于使用带有空参数的 .end() 方法来表示和结束而不传递要呈现的数据的具体内容。我已经用谷歌搜索了这个,但我还没有答案。
【问题讨论】:
-
你能发布完整的工作代码吗?
-
When I comment out the res.end() command, the view displays all of the messages,你是怎么做到的?您的代码没有显示client.end()的任何逻辑 -
@abhyudit-jain,server.js 文件的完整工作代码现已发布在上面,提前感谢您的想法
-
@abhyudit-jain 我也添加了 html 文件
-
@shaochuancs 我不明白你的评论,你能改写一下吗?我所知道的是,如果我注释掉 res.end(),则会显示消息,但浏览器会继续期待更多数据。
标签: javascript node.js http server