node.js Express - res.send() 工作一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15249808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express - res.send() works once
提问by Mahdi Dibaiee
I'm new to Node and Express, I was trying to make something with Express just to get started, then I faced this problem.
我是 Node 和 Express 的新手,我试图用 Express 做一些东西只是为了开始,然后我遇到了这个问题。
First res.send()works well, but the second one doesn't fire.
第一个res.send()效果很好,但第二个不火。
Here's my code:
这是我的代码:
var express = require('express'),
app = express(),
fs = require('fs'),
visits;
app.listen(8080);
app.get('/', function(req,res) {
res.send('Hello');
fs.readFile('counter.txt','utf-8', function(e,d) {
if (e) {
console.log(e);
}
else {
console.log(parseInt(d) + 1);
fs.writeFile('counter.txt',parseInt(d) + 1);
res.send('<p id="c">' + ( parseInt(d) + 1 ) + '</p>');
}
})
...
'Hello' is sent, but res.send('<p> .. </p>');isn't. If I comment res.send('Hello');, visitors will be shown.
'Hello' 被发送,但res.send('<p> .. </p>');不是。如果我发表评论res.send('Hello');,将显示访问者。
Thanks in advance.
提前致谢。
采纳答案by robertklep
res.send()is meant to be called just once.
res.send()意味着只被调用一次。
Try this instead:
试试这个:
app.get('/', function(req,res) {
var response = 'Hello';
fs.readFile('counter.txt','utf-8', function(e,d) {
if (e) {
console.log(e);
res.send(500, 'Something went wrong');
}
else {
console.log(parseInt(d) + 1);
fs.writeFile('counter.txt',parseInt(d) + 1);
response += '<p id="c">' + ( parseInt(d) + 1 ) + '</p>';
res.send(response);
}
})
});
(or just res.send("Hello<p id=..."), but you get the point :)
(或者只是res.send("Hello<p id=..."),但你明白了:)
回答by user568109
This is because res.send() finishes sending the response.
这是因为 res.send() 完成发送响应。
When res.send('Hello');is encountered it sends the response immediately. So next res.sendis not executed and you cannot see visitors. Commenting the first res.sendallows you to view the second one.
当res.send('Hello');遇到它时,它立即发送响应。所以 nextres.send没有执行,你看不到访客。评论第一个res.send允许您查看第二个。

