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 Populating User Information

Matt Ehlinger
Matt Ehlinger
4,916 Points

User route not serving?

I can't seem to get the user route to populate the page with information when I run the server. When I run 'localhost:3000' I get the desired response. However, when I add a username afterwards (i.e. 'localhost3000/chalkers') the session eventually times out.

I don't understand what it is I'm missing. Could it be that I need to change the url to when adding a username since I'm running everything locally rather than in workspaces? Or have I completely missed something in my code?

Thanks!

app.js:

var router = require('./router.js');

// Create the web server
const http = require('http');

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

const server = http.createServer( (request, response) => {
    router.home(request, response); 
    //router.user(request, response); 
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

router.js:

var Profile = require("./profile.js");

// Handle the http route GET / and POST / i.e. Home
const homeRoute = (request, response) => {
    // if url == '/' && GET 
    if(request.url === "/") {
        // show search field
        response.statusCode = 200;
        response.setHeader('Content-Type', 'text/plain');   
        response.write('Header\n');
        response.write('Search\n');
        response.end('Footer\n');
    }

    // if url == '/' && POST
        // redirect to /:username
}

// Handle the http route for GET /:username i.e. /veryspry
const userRoute = (request, response) => {

    var username = request.url.replace('/', '');


    if (username > 0) {
        response.statusCode = 200;
        response.setHeader('Content-Type', 'text/plain');   
        response.write('Header\n');

        // get json from treehouse

        var studentProfile = new Profile(username);
        console.log(studentProfile);
        // on the end
        studentProfile.on("end", function(profileJSON) {
            // show the profile

            // Store the values that we need
            var values = {
                avatarURL: profileJSON.gravatar_url,
                username: profileJSON.profile_name,
                badges: profileJSON.badges.length,
                javascriptPoints: profileJSON.points.JavaScript
            }
            // Simple response
            response.write(values.username + 'has' + values.badges + '\n');
            response.end('Footer\n');

        }); 

        // on error
        studentProfile.on("error", function(error) {
            // Show error
            response.end('Footer\n');
        }); 

        // if url == '/.....'       
    }
}

module.exports.home = homeRoute;
module.exports.user = userRoute;

profile.js:

var EventEmitter = require("events").EventEmitter;
var https = require("https");
var http = require("http");
var util = require("util");

/**
 * An EventEmitter to get a Treehouse students profile.
 * @param username
 * @constructor
 */
function Profile(username) { 

    EventEmitter.call(this);

    profileEmitter = this;

    //Connect to the API URL (https://teamtreehouse.com/username.json)
    var request = https.get("https://teamtreehouse.com/" + username + ".json", function(response) {
        var body = "";

        if (response.statusCode !== 200) {
            request.abort();
            //Status Code Error
            profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
        }

        //Read the data
        response.on('data', function (chunk) {
            body += chunk;
            profileEmitter.emit("data", chunk);
        });

        response.on('end', function () {
            if(response.statusCode === 200) {
                try {
                    //Parse the data
                    var profile = JSON.parse(body);
                    profileEmitter.emit("end", profile);
                } catch (error) {
                    profileEmitter.emit("error", error);
                }
            }
        }).on("error", function(error){
            profileEmitter.emit("error", error);
        });
    });
}

util.inherits( Profile, EventEmitter );

module.exports = Profile;
Joel Bardsley
Joel Bardsley
31,246 Points

It looks like you've pasted app.js twice instead of showing us router.js. Could you edit your post to show router.js?

Matt Ehlinger
Matt Ehlinger
4,916 Points

Ahh, dumb mistake. Thanks, Joel! Code is updated.