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

Page will not load

Can anyone tell me why my page will not load? Whenever I type localhost:3000 in the browser, it just keeps loading, and never displays anything.

I should say that I am using localhost:3000 because I am using my local environment. It's been working fine up til this point.

const http = require("http");

const port = 3000;

const server = http
  .createServer((request, response) => {
    homeRoute(request, response);
  })
  .listen(port);
console.log(`Server listening at port ${port}`);

const homeRoute = (request, response) => {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("Header\n");
  response.write("Search\n");
  response.write("Footer\n");
};

1 Answer

I got it working. I think it's because I didn't put

response.end("Footer\n");

Here is my code now, that works:

const http = require("http");
const port = 3000;

const server = http
  .createServer((request, response) => {
    homeRoute(request, response);
  })
  .listen(port, () => {
    console.log(`Server listening at port ${port}`);
  });

const homeRoute = (request, response) => {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("Header\n");
  response.write("Search\n");
  response.end("footer\n");
};
J llama
J llama
12,631 Points

Thanks bro. I forgot it too! Gotta end the response before we can write to the server! Thx for the help honestly the first time any one has put anything useful in here for me at least, the treehouse instructors don't do a very good job imo