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

Bit stuck / nodejs dynamic website

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


//Handle the http route GET and POST ie home 
    function home(request, response) {
    if (request.url === "/") {
    //if the url == "/" && GET 
    //show search
                response.writeHead(200, {"content-type":"text/plain"});
                response.write("Header\n");
                response.write("Search\n");     
                response.end("Footer\n");
                }
    //if the url == "/" && POST 
        // redirect to username
                            }                   

//Handle the http get url ie .../username
    //if the url == "/..."
    function user(request, response) {
        var username = request.url.replace("/", "");
            if (username.length > 0) {
                response.writeHead(200, {"content-type":"text/plain" "charset":"utf-8"});
                response.write("Header\n");

                //get json from treehouse 
                var studentProfile = new Profile(username);

                //on end 
                studentProfile.on("end", function(profileJSON) {
                var values = {
                    avatarUrl: profileJSON.gravatar_url,
                    userName:   profileJSON.profile_name,
                    Javascript: profileJSON.points.JavaScript,
                    Badges: profileJSON.Badges.total                

                }
                //show profile

                response.write(values.userName + " has " + values.Javascript + " Javascript points. " + "\n");
                response.end("Footer\n");
                });


                //on error 
                studentProfile.on("error", function(error) {

                //show error
                response.end("Footer\n");
                });





          }
                                                }

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

The response is still the same just header and footer ? I has a look at the error message and the only one is "The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature."

Ihave tried adding this at the top but not sure if im doing it right or if thats what is causing the problem?

rydavim
rydavim
18,813 Points

You can add the language right after your opening backticks when posting code to get fancy syntax highlighting, which I've added to your post. :)

3 Answers

rydavim
rydavim
18,813 Points

This is going to seem a bit silly, but it looks like the problem is that you capitalized the b in badges.

var values = {
        avatarUrl: profileJSON.gravatar_url,
        userName:   profileJSON.profile_name,
        Javascript: profileJSON.points.JavaScript,
        Badges: profileJSON.badges.total   // Don't capitalize badges in badges.total here.             
      };

That fixed your code for me, but let me know if that doesn't work for you. Happy coding! :)

Thanks but still not working for me, I took away the values object and just tried getting the status code but its not getting anything, the only thing tat comes through on the response is header ?

rydavim
rydavim
18,813 Points

Whoops! There was one other thing I changed. I took out the "charset":"utf-8", which was causing it to not run at all for me.

I sort of doubt that's your issue though. My guess at this point is that the problem lies in your profile.js file. Since I'm running your router.js code against my own code, it may be that our profile files are different.

The profile file gets a bit wonky, because Treehouse changed their profile api to use https instead of http. This complicates things, as you'll need to use both - https to fetch the profile data, and http to handle the errors.

That might be enough to get you on the right track. If you run into issues though, I'm happy to help if you post your profile.js code here. The solution will not match the teacher's finished file, as they were using http at the time of the videos.

Sorry, I completely forgot about that and that it might cause issues for you.

Yea i have tried it without the charset bit, I only put that in because of an error I was getting about encoding ? I dont know what it is i have tried it lots of different ways and simplified bits, the code is running fine its just not fetching the profile as you said but I havent changed anything in the profile.js file because it was all in the project files download. I think i might just start it again, but thanks anyway.

rydavim
rydavim
18,813 Points

Right, what I'm saying is that the profile.js file that is in the project files download will not work. They have changed the way you access the api since the making of that video. If you post the code here, I can help you fix it to work with the new access method.

Edit: The charset warning is due to the head not having a meta tag that identifies the character encoding. You can add that later once you've got to the point that you're generating an actual website, rather than text.

rydavim
rydavim
18,813 Points

Actually, if you're using the project files anyway, you're welcome to try my code if you like.

Here is my profile.js code, which works with your router.js assuming the small changes detailed above.

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

function Profile(username) {
  EventEmitter.call(this);
  profileEmitter = this;
  // connect to new 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 handling
      profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
    }
    // read the profile data
    response.on('data', function (chunk) {
      body += chunk;
      profileEmitter.emit("data", chunk);
    });
    response.on('end', function () {
      if(response.statusCode === 200) {
        try {
          // parse the profile 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;

Let me know if you have any questions, but that should let you advance your project to the next step.

Hey got it working, thanks for the help, I did have the right project files but i tried it again and it worked, i think you were right the first time , I was accessing the JSON object wrong, but its working now.

rydavim
rydavim
18,813 Points

Good to hear, happy coding! :)