Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,275 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