简体   繁体   中英

Write after end error when launch server in nodejs

I am beginner at NodeJS and I'm doing a "NodeJS and Express.js full course" at freecodecamp yt and I copied author code which for him works perfectly, but I got an error.

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 us')
}
res.end('Error')
})

server.listen(3000, ()=>{
    console.log('Server listening...');
})

I don't know why he got home, about and error page when user goes to the wrong page it should throw "Error" text on page, but instead my program is throwing an error in nodeJS program:

events.js:377
    throw er; // Unhandled 'error' event
     ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (internal/errors.js:322:7)
    at writeAfterEnd (_http_outgoing.js:694:15)
    at ServerResponse.end (_http_outgoing.js:815:7)
    at Server.<anonymous> (C:\Users\jonat\Desktop\nodejs\app.js:10:5)
    at Server.emit (events.js:400:28)
    at parserOnIncoming (_http_server.js:900:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:127: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'
}

Can someone explain this to me? I would be appreciate. Thank you in advance.

That's caused by the res.end('Error') , which gets always executed. Try to put it into an else clause, or put a return before each res.end(…)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM