I created a file http1.js. In browser, when I type localhost:5000/about I get localhost refused to connect and in code I got the error:
const http = require('http')
const server = http.create Server((req, res) => {
if (req.url === '/') {
res.end('Welcome to our home page')
}
if (req.url === '/about') {
res.end('Here is our short history')
}
res.end(
`<h1>Oops!</h1>
<p>We can't seem to find the page your are looking for</p>
<a h ref ="/">Back home page</a>`
)
}
)
server.listen(5000)
The exception thrown is this one when I type localhost:5000/about and refresh the page this is the error which I am encountering in my code. How to solve it, and also but there is no issue when I type localhost:5000 I got correct result.
node:events:490
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:399:5)
at ServerResponse.end (node:_http_outgoing:1009:15)
at Server.<anonymous> (c:\Users\Suresh\pratice_Tuotorial(JN)\.vscode\tempCodeRunnerFile.js:9:9)
at Server.emit (node:events:512:28)
at parserOnIncoming (node:_http_server:1086:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:849:9)
at process.processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
You're giving two responses when accessing
localhost:5000/aboutandlocalhost:5000/. After telling the http-client (e.g.browser) that it won't receive more from the server with theresponse.end().Here's how you have to do, for giving just one response always:
Now, this code just returns one response.
If you want to understand why your code didn't return an
Exceptionwhen typinglocalhost:5000, it was because your code did not execute the contents in anyifand just returned one response.localhost:5000: one response -> OKlocalhost:5000/: two responses -> Exceptionlocalhost:5000/about: two responses -> ExceptionIf you need to send more than one response, the way is using
response.write()instead ofresponse.end(). Here's more information .