Where's the error in the code? Node.js error code ERR_STREAM_WRITE_AFTER_END

141 views Asked by At

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'
  }
1

There are 1 answers

0
tremendows On BEST ANSWER

You're giving two responses when accessing localhost:5000/about and localhost:5000/. After telling the http-client (e.g.browser) that it won't receive more from the server with the response.end().

Here's how you have to do, for giving just one response always:

const http = require('http')
const server = http.create Server((req, res) => {

    if (req.url === '/') {
        res.end('Welcome to our home page')
    } else if (req.url === '/about') {
        res.end('Here is our short history')
    } else {
        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>`
        )
    }
}
)

Now, this code just returns one response.

If you want to understand why your code didn't return an Exception when typing localhost:5000, it was because your code did not execute the contents in any if and just returned one response.

  1. localhost:5000: one response -> OK
  2. localhost:5000/: two responses -> Exception
  3. localhost:5000/about: two responses -> Exception

If you need to send more than one response, the way is using response.write() instead of response.end(). Here's more information .