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!

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

Catalin Voineag
Catalin Voineag
7,823 Points

Trying to connect to localhost API

OK, so now I changed some of my code, but there is still a problem. I want to display the information from profile.js in to router.js like this: response.write("My name is:" + profile + "\n"); , or something similar. Now the app displays: HEADER My name is:[object Object] Footer

app.js file:

var router = require('./router.js'); //Problem: We need a simple way to look at a person's name, address, phone number and pictures //Solution: Use Node.js to perform the profile look ups and serve our template via HTTP

// Create a web server var http = require('http'); http.createServer(function (request, response){ router.home(request, response);

}).listen(8080, "127.0.0.1"); console.log("Server running at localhost:3000");

profile.js file:

var http = require("http");

function printMessage(person) { var message = "My name is " + person document.write(printMessage()); }

var request = http.get("http://localhost:8080/person", function(response){ var body = ""; //Read the data response.on('data', function(chunk) { body += chunk; }); response.on('end', function(){ var person = JSON.parse(body); var profile = person[0].name.firstName; }); request.on("error", function(error){ response.end("ERROR"); });

});

router.js file:

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

//Handle HTTP route GET / and POST / i.e. Home function home(request, response) { //if url == "/" && GET if(request.url === "/"){ //show index page response.writeHead(200, {'Content-Type': 'text/plain'}); response.write("HEADER\n");

    response.write("My name is:" + profile + "\n");


    response.end("Footer\n");


}

} module.exports.home = home;

3 Answers

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Does it work? I'm unsure if you're having an issue or just showing your code.

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Where is the "name" variable coming from in new Profile(name)?

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

You haven't given the full router.js file. You've only shown 8 lines and this says its on line 11...