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 HTTP Methods and Headers Sending Content Type Headers in Node.js

Vishrut Kaila
PLUS
Vishrut Kaila
Courses Plus Student 4,871 Points

There was an error getting the profile for hellochalkers (Found) statusCode is 302 for invalid profiles & 404 for valid

Can't find the reason why statusCode for valid profiles is 404 and invalid profiles is 302. Please look at the files below.

//File: 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/profiles/${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;

//File: renderer.js

var fs = require("fs");

function mergeValues (values, content){ //Cycle over the keys for (var key in values){ //Replace all the {{keys}} with the value from the values object content = content.replace("{{" + key + "}}", values[key]); } //Return merged content return content; };

function view(templateName, values, response){ //Read from the template files var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"}); //Insert values into the content fileContents = mergeValues(values, fileContents); //Write out to the response response.write(fileContents); } module.exports.view = view;

//File: router.js

var Profile = require("./profile.js"); var renderer = require("./renderer.js"); var commonHeaders = { 'Content-Type': 'text/html' };

//Handle HTTP route GET / and POST / i.e. Home. function home (request, response) { // if the url == "/" && GET if (request.url === "/"){ // show search response.writeHead(200, commonHeaders); renderer.view("header", {}, response); renderer.view("search", {}, response); renderer.view("footer", {}, response); response.end(); } //response.end('Hello World\n'); // if url == "/" && POST // redirect to /:username
} //Handle HTTP route GET /:username i.e. /chalkers or /kaila. function user (request, response){ // if url == "/..." var username = request.url.replace("/",""); if (username.length > 0){ response.writeHead(200, commonHeaders); renderer.view("header", {}, response);

    // get JSON from Treehouse
    var studentProfile = new Profile(username);
    // on "end"
    studentProfile.on("end", function(profileJSON){
      // show profile

      // Store the value which we need
      var values = {
        avatarURL: profileJSON.gravatar_url,
        username: profileJSON.profile_name,
        badges: profileJSON.badges.length,
        javascrpitPoints: profileJSON.points.JavaScript
      }

      // Simple response
      renderer.view("profile", values, response);
      renderer.view("footer", {}, response);
      response.end();
    });
    // on "error"
    studentProfile.on("error", function(error){
    // show error
      renderer.view("error", {errorMessage : error.message}, response);
      renderer.view("search", {}, response);
      renderer.view("footer", {}, response);
      response.end();
    });
}

}

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

Steven Parker
Steven Parker
231,275 Points

When posting code, use Markdown formatting to preserve the code's appearance. Even better, you can share an entire project by making a snapshot of your workspace and posting the link to it here.

1 Answer

Steven Parker
Steven Parker
231,275 Points

From answering a previous question, I'm aware that the server now sends a redirect (302) to an information page when you attempt to access an invalid profile name. So that behavior is correct. You might want to contact Support to suggest they add something to the Teacher's Notes to explain the new system.