Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Handling Routes in Node.js Home Route

Error: Can't set headers after they are sent.

I don't get it, where the error is. How do I find out in which line the error is?

I get the following error message in the console:

throw new Error('Can\'t set headers after they are sent.');                 

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at Server.<anonymous> (/home/treehouse/workspace/app.js:14:12)
at emitTwo (events.js:87:13)
at Server.emit (events.js:172:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:103:23)

and here is the code:

const http = require('http');

const hostname = ''; const port = 3000;

const server = http.createServer((request, response) => { response.statusCode = 200; response.write("This is before the end"); setInterval(function(){ response.write(new Date() + "/n"); }, 1000); response.setHeader('Content-Type', 'text/plain'); response.end('Hello World\n'); });

server.listen(3000), console.log(Server running at http://${hostname}:${port}/);

1 Answer

Jesus Mendoza
Jesus Mendoza
23,288 Points

You can't write multiple responses because after you write it you have to end it and after you end it you can't send anything else