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 User Route

Sandro Das Neves
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Sandro Das Neves
Front End Web Development Techdegree Graduate 23,426 Points

how to type the good url ?

I've the exact same code but in my local machine when I add /username at the end of the url it doesn't do anything. can someone help me please ?

Alex Thomas
Alex Thomas
4,247 Points

you may have the wrong target, can you post your code?

Sandro Das Neves
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Sandro Das Neves
Front End Web Development Techdegree Graduate 23,426 Points
const router = require('./router.js');
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    router.home(req,res);
    router.user(req,res);
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
function home(req,res) {
    if (req.url === "/") {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.write('Header\n');
        res.write('Search\n');
        res.end('Footer\n');
    }
}

function user(req,res) {
    const username = req.url.replace("/","");
    if (username.lenght > 0) {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.write('Header\n');
        res.write(username + '\n');
        res.end('Footer\n');
    }
}

module.exports.home = home;
module.exports.user = user;

the first is in an example.js file and the second in the router.js fils

1 Answer

Hi Sandro, I had the same problem , it is because the documentation has slightly changed and the copy-paste-example from node.js.org uses the setHeader-method. You can set that method only once (with me this was a message in the console), and after I removed the res.setHeader from the user-function all works fine.