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

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

User route

I still don't understand why we're replacing the "/" with an empty string for the user route. Isn't the "/" part of the request? (i.e. "/chalkers")

2 Answers

Neil McPartlin
Neil McPartlin
14,662 Points

Hi Leo. Let's just focus on what Andrew has done in the first 2 minutes of this video. His code up to that point, just for the userRoute, is as shown below...

//Handle HTTP route GET /:username i.e. /chalkers
function  userRoute(request, response) {
    //if URL == '/...'
    var username = request.url.replace('/', '');
    if(username.length > 0) {

        //get JSON from treehouse    
            //on 'end'
                //show profile
            //on 'error'
                //show error

We are writing code for a website but think of it as 2 locations. What a user 'requests' on their browser (local computer), and how our server 'responds' to their request. A user has submitted a request for badge information for 'leomarcocorpuz'. This action results in a GET request being sent to our server using 'https://teamtreehouse.com/leomarcocorpuz'.

We currently have 2 routes defined in the app.js file. There is a '/' detected in the GET request so the userRoute will be the one that determines what response gets sent back to the user.

The first thing we need to isolate is the username, so everything after the domain name including the '/' gets extracted i.e. /leomarcocorpuz. Finally, in order to extract the actual username, we need to effectively remove the '/' by replacing it with ' ' (i.e. nothing).

So long story short, we are not 'creating' a URL, we are simply 'reading' a URL in order to decide what information to send back to the user.

So why wouldn't we use url/username.slice() method to get just the username? If we replace '/' with empty string we will get "url username" instead of username only.