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

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.

Piotr Manczak
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Piotr Manczak
Front End Web Development Techdegree Graduate 28,940 Points

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.