Reputation: 95
I am learning node.js and want to open a server with a simple home, about, and error page. I (seem to have) followed the syntax exactly, but each time I load a request from the server in my browser, the page loads but I get an error in the vsCode terminal and the port closes. Here is my code:
const http = require('http')
const server = http.createServer((req, res)=>{
if(req.url ==='/'){
res.end('Home Page')
}
if(req.url ==='/about'){
res.end('about page')
}
res.end("error")
})
server.listen(5000, ()=>{
console.log("server is listening at port 5000...")
})
and here is the error I am getting:
server is listening at port 5000...
events.js:353
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:694:15)
at ServerResponse.end (_http_outgoing.js:815:7)
at Server.<anonymous> (/home/nick/node-tutorial/app.js:11:5)
at Server.emit (events.js:376:20)
at parserOnIncoming (_http_server.js:896:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:753:7)
at processTicksAndRejections (internal/process/task_queues.js:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Upvotes: 0
Views: 3878
Reputation: 707456
You are calling res.end()
twice from your request handler when you get either the /
or /about
requests. You can only call it once.
You end up calling res.end()
more than once because when your request matches either /
or /about
, you call res.end()
for those specific pages and then you have another res.end()
at the end of the function that also executes.
To fix it, change to this:
const server = http.createServer((req, res)=>{
if (req.url ==='/') {
res.end('Home Page')
} else if (req.url ==='/about') {
res.end('about page')
} else {
res.statusCode = 404;
res.end("error")
}
});
Keep in mind that res.end()
does not stop your function from continuing to execute. So, if you don't want to execute any more code in the function after calling res.end()
, you need to either protect it with conditionals like I did above or add a return
after you call res.end(...)
.
FYI, your specific error 'ERR_STREAM_WRITE_AFTER_END'
is because res.end()
writes out data to the stream and then closes the stream. So, the second time you try to call res.end()
, it tries to write data to an already-closed stream which gives you the error you saw.
Upvotes: 1