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

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Dynamic values not showing up on localhost

Hi all,

Right, so I've managed to change the file headers to display HTML but when I test the site on localhost none of the values from the JSON feed are showing up properly. The text values and the gravar image are missing.

Error on Node

Any ideas how this could be? heres my code.

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

var commonHeader = {'content-type': 'text/html'};

//Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
  //if url == "/" && GET
  if(request.url === "/") {
    //show search
    response.writeHead(200, commonHeader);  
    renderer.view("header", {}, response);
    renderer.view("search", {}, response);
    renderer.view("footer", {}, response);
    response.end();
  }
  //if url == "/" && POST
    //redirect to /:username
}

//Handle HTTP route GET /:username i.e. /chalkers
function user(request, response) {
  //if url == "/...."
  var username = request.url.replace("/", "");
  if(username.length > 0) {
    response.writeHead(200, commonHeader);  
    renderer.view("header", {}, response);    

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

      //Store the values which we need
      var values = {
        avatarURL: profileJSON.gravatar_url, 
        username: profileJSON.profile_name,
        badges: profileJSON.badges.length,
        javascriptPoints: 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();
    });

  }
}

//export routes to app.js]
module.exports.home = home;
module.exports.user = user;
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;

Thanks

Seth Kroger
Seth Kroger
56,414 Points

What about your renderer.js?

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,253 Points
var fs = require("fs");


/*File for reading the content of HTML templates and their values*/ 

function mergeValues(values, content) {
    //Cycle over the keys
    for (var key in values) {
        //Replace all {{key}} with the value from the values object

        content = content.replace("{{" + key + "}}", values[key]);
    }

    //return merged content
    return content;
}


//a function to read file contents, - HTML from a view file
function view(templateName, values, reponse) {
  //Read from the template file
  var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"});
  //Insert values in to the content

  //Write out the contents to the response
  reponse.write(fileContents);
}

module.exports.view = view;

1 Answer

Seth Kroger
Seth Kroger
56,414 Points

Looks like you forgot to call mergeValues before writing the template to the response.

//a function to read file contents, - HTML from a view file
function view(templateName, values, reponse) {
  //Read from the template file
  var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"});
  //Insert values in to the content
  fileContents = mergeValues(values, fileContents);
  //Write out the contents to the response
  reponse.write(fileContents);
}
Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,253 Points

Yup, that's the one thanks.

Also had to fix my view files to correct the expressions. Started to butcher the HTML files when trying to get the details to display ;)