Express - res.send () works once

I am new to Node and Express, I tried to do something with Express just for a start, and then I ran into this problem.

The first res.send() works well, but the second does not work.

Here is 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>'); - not. If I comment on res.send('Hello'); , visitors will be shown.

Thanks in advance.

+8
express
source share
2 answers

res.send() intended to be called only once.

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 :)

+6
source share

This is because res.send () terminates the response.

When res.send('Hello'); is res.send('Hello'); He immediately sends a response. Therefore, the next res.send not executed, and you cannot see visitors. Commenting on the first res.send , you can view the second.

+3
source share

All Articles